关于对象存入NSUserDefaults

 

#import <Foundation/Foundation.h>

 

@interface Student : NSObject <NSCoding>

@property (nonatomic ,copy)NSString * name;

@property (nonatomic ,copy)NSString * contact;

@end

#import "Student.h"

 

@implementation Student

 

- (void)encodeWithCoder:(NSCoder *)aCoder

{

    [aCoder encodeObject:self.name forKey:@"name"];

    [aCoder encodeObject:self.contact forKey:@"contact"];

}

 

- (instancetype)initWithCoder:(NSCoder *)aDecoder

{

    if (self = [super init]) {

        

        self.name = [aDecoder decodeObjectForKey:@"name"];

        self.contact = [aDecoder decodeObjectForKey:@"contact"];

        

    }

    return self;

}

 

@end

 

 

#import "ViewController.h"

#import "Student.h"

 

@interface ViewController ()

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    

    Student * xiaoli = [[Student alloc]   init];

    xiaoli.name = @"sujianbo";

    xiaoli.contact = @"18811569851";

    

    NSData * data = [NSKeyedArchiver archivedDataWithRootObject:xiaoli];

    

    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];

    [user setObject:data forKey:@"su"];

    [user synchronize];

    

    NSData * su = [user objectForKey:@"su"];

    Student * jian = [NSKeyedUnarchiver unarchiveObjectWithData:su];

    NSLog(@"name--->%@,contact---->%@",jian.name,jian.contact);

 

}

 @end

 

------------打印信息

2016-03-04 09:34:08.904 NSUserDefaults[943:25413] name--->sujianbo,contact---->18811569851

 

posted @ 2016-03-04 09:44  sujianbo  阅读(106)  评论(0编辑  收藏  举报