标签:
//以下是我用 NSUserDefaults 将 NSData 类型的地址数组存在本地。
UserAddressEntity *userAddressEntity = [[UserAddressEntity alloc]init]; userAddressEntity.addName = addName.text; userAddressEntity.addPhone = addPhone.text; userAddressEntity.addressInfo = [NSString stringWithFormat:@"%@%@",baseAddress.text,detailAddress.text]; //实例 NSUserDefaults 类 NSUserDefaults *address = [NSUserDefaults standardUserDefaults]; //获取本地 address 数据,记得将取出来的不可变 NSArray 转成 可变的 NSMutableArray ,可以用alloc 方法代替 NSMutableArray *mutableArray = [NSMutableArray arrayWithArray:[address objectForKey:@"AddressArray"]]; //将 userAddressEntity 对象转成 NSData 类型 NSData *data = [NSKeyedArchiver archivedDataWithRootObject:userAddressEntity]; //存放数据的数组将 data 加入进去 [mutableArray addObject:data]; //记住要转换成不可变数组类型 NSArray * array = [NSArray arrayWithArray:mutableArray]; [address setObject:array forKey:@"AddressArray"];//以下是 UserAddressEntity.h
// UserAddressEntity.h // SXH // // Created by Jack on 15/9/15. // Copyright (c) 2015年 lyss. All rights reserved. // #import <Foundation/Foundation.h> @interface UserAddressEntity : NSObject @property (nonatomic, strong) NSString *addName; @property (nonatomic, strong) NSString *addPhone; @property (nonatomic, strong) NSString *addressInfo; // - (instancetype)initWithAttributes:(NSDictionary *)attributes; @end
//以下是 UserAddressEntity.m
// // UserAddressEntity.m // SXH // // Created by Jack on 15/9/15. // Copyright (c) 2015年 lyss. All rights reserved. // #import "UserAddressEntity.h" @implementation UserAddressEntity @synthesize addName,addPhone,addressInfo; - (instancetype)initWithAttributes:(NSDictionary *)attributes { self = [super init]; if (!self) { return nil; } self.addName= [attributes valueForKeyPath:@"addName"]; self.addPhone = [attributes valueForKeyPath:@"addPhone"]; self.addressInfo = [attributes valueForKeyPath:@"addressInfo"]; return self; } /** * 将对象写入文件的时候调用 * 怎样存储 * 转成 NSDate 类型前的编码 * @param aCoder aCoder */ - (void)encodeWithCoder:(NSCoder *)encoder{ [encoder encodeObject:self.addName forKey:@"addName"]; [encoder encodeObject:self.addPhone forKey:@"addPhone"]; [encoder encodeObject:self.addressInfo forKey:@"addressInfo"]; } - (id)initWithCoder:(NSCoder *)decoder{ if(self = [super init]) { self.addName = [decoder decodeObjectForKey:@"addName"]; self.addPhone = [decoder decodeObjectForKey:@"addPhone"]; self.addressInfo = [decoder decodeObjectForKey:@"addressInfo"]; } return self; } @end
ps:
//获取 本地数据
NSUserDefaults *address = [NSUserDefaults standardUserDefaults];
mutableArrayAddress = [NSMutableArray arrayWithArray:[address objectForKey:@"AddressArray"]];
//获取 数组中 第一个 NSData 类型的值
UserAddressEntity *addressEntity = [NSKeyedUnarchiver unarchiveObjectWithData:[mutableArrayAddress objectAtIndex:0];
NSUserDefaults 存储数据到本地,NSUserDefaults 使用
标签:
原文地址:http://my.oschina.net/jack088/blog/506460