一:NSUserDefaults支持的数据格式有:NSNumber(Integer、Float、Double),NSString,NSData,NSArray,NSDictionary,BOOL类型;
二:可以把自定义的对象,转换为NSData来达到存储对象到NSUserDefaults的目的;
如代码:
1:model.h
#import <Foundation/Foundation.h> @interface ReplayModel : NSObject @property (nonatomic,strong)NSNumber *useTimes; //使用次数 @property (nonatomic,strong)NSDate *addDate; //添加日期 @property (nonatomic,strong)NSString *replayContent; //回复的模板内容; @end
2: model.m
#import "ReplayModel.h" @implementation ReplayModel - (void)encodeWithCoder:(NSCoder *)encoder { //Encode properties, other class variables, etc [encoder encodeObject:self.useTimes forKey:@"useTimes"]; [encoder encodeObject:self.addDate forKey:@"addDate"]; [encoder encodeObject:self.replayContent forKey:@"replayContent"]; } - (id)initWithCoder:(NSCoder *)decoder { if((self = [super init])) { //decode properties, other class vars self.useTimes = [decoder decodeObjectForKey:@"useTimes"]; self.addDate = [decoder decodeObjectForKey:@"addDate"]; self.replayContent = [decoder decodeObjectForKey:@"replayContent"]; } return self; } @end
3: 使用,写入
ReplayModel *model = [pinCiDataArray objectAtIndex:theReplayIndex]; NSLog(@"%@ 次数 %d",model.replayContent,[model.useTimes intValue]); model.useTimes = [NSNumber numberWithInt:[model.useTimes intValue]+1]; NSLog(@"新次数 %d",[model.useTimes intValue]); [pinCiDataArray replaceObjectAtIndex:theReplayIndex withObject:model]; NSData *encodeData = [NSKeyedArchiver archivedDataWithRootObject:pinCiDataArray]; [[NSUserDefaults standardUserDefaults] setObject:encodeData forKey:kPiCiArrayData];
4:使用,读取
NSData *encodeObject = [[NSUserDefaults standardUserDefaults] objectForKey:kTimeArrayData];
NSMutableArray *tempTimeData = [NSKeyedUnarchiver unarchiveObjectWithData:encodeObject];
参考:http://stackoverflow.com/questions/2315948/how-to-store-custom-objects-in-nsuserdefaults