userdefault 保存对象数据,data数据本地保存

调用

//首先,要建立一个可变数组来存储 NSDate对象 
Model *student = [[Model alloc] init]; 
//下面进行的是对student对象的 name , studentNumber ,sex 的赋值
student.name = @"微微一笑很倾城";
student.age = 111111; 
//将student类型变为NSData类型
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:student];
NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
[user setObject:data forKey:@"oneStudent"];
[user synchronize];

-(void)Createf{
NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
NSData *data = [user objectForKey:@"oneStudent"];
Model *student = [NSKeyedUnarchiver unarchiveObjectWithData:data];

NSLog(@"~~~~%@",student.name);
NSLog(@"~~~~%d",student.age);

}

//model 文件

import

@interface Model : NSObject

/*!
*名
*/
@property(nonatomic,strong)NSString name;
/
!
*年龄
*/
@property(nonatomic,assign)NSInteger age;;
@end

import "Model.h"

@implementation Model
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeObject:[NSNumber numberWithInteger:self.age] forKey:@"age"];

}
-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
if (self == [super init]) {
self.name = [aDecoder decodeObjectForKey:@"name"];
NSNumber * number = [aDecoder decodeObjectForKey:@"age"];
self.age = number.integerValue;

}
return self;

}

@end

你可能感兴趣的:(userdefault 保存对象数据,data数据本地保存)