2012年3月13日

[iPhone]使用NSUserDefaults將自定義的Object存入手機


首先在自己的Object中加上
@interface YourObject : NSObject<NSCoding>
{
   
NSString *string_a;
   
NSString *string_b;
    int int_c;
}

然後在這個Object中加上encoderWithObject:initWithObject:兩個方法
-(void)encodeWithCoder:(NSCoder *)encoder

{
   [encoder encodeObject:string_a forKey:@"string_a"];
   [encoder encodeObject:string_b forKey:@"string_b"];
   [encoder encodeInt:int_c forKey:@"int_c"];
}


-(id)initWithCoder:(NSCoder *)decoder

{
    self.string_a = [decoder decodeObjectForKey: @"string_a"];
    self.string_b = [decoder decodeObjectForKey: @"string_b"];
    self.int_c = [decoder decodeObjectForKey:@"int_c"];
    return self;
}

存入的方法
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
YourObject *obj = [[YourObject alloc]init];
NSMutableArray *arr = [[NSMutableArray alloc]initWithObject:obj,nil];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:arr];
[defaults setObject:data forKey:@"theKey"];

讀取的方法
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [defaults objectForKey:@"theKey"];
NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithData:data];

沒有留言: