需要写入的对象必须实现NSCoding protocol
Person Class
Person.h #import <Foundation/Foundation.h> #import "Face.h" @interface Person : NSObject <NSCoding> @property (nonatomic, strong) NSString *personId; @property (nonatomic, strong) NSString *name; @property (nonatomic, assign) NSInteger age; @property (nonatomic, strong) NSArray *photos; @property (nonatomic, strong) NSDictionary *phoneNumber; @property (nonatomic, strong) Face *face; @end Person.m #import "Person.h" @implementation Person @synthesize personId = _personId; @synthesize name = _name; @synthesize age = _age; @synthesize photos = _photos; @synthesize phoneNumber = _phoneNumber; @synthesize face = _face; - (id)initWithCoder:(NSCoder *)aDecoder { if(self = [super init]) { self.personId = [aDecoder decodeObjectForKey:@"id"]; self.name = [aDecoder decodeObjectForKey:@"name"]; self.age = [[aDecoder decodeObjectForKey:@"age"] integerValue]; self.photos = [aDecoder decodeObjectForKey:@"photos"]; self.phoneNumber = [aDecoder decodeObjectForKey:@"phoneNumber"]; self.face = [aDecoder decodeObjectForKey:@"face"]; } return self; } - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:self.personId forKey:@"id"]; [aCoder encodeObject:self.name forKey:@"name"]; [aCoder encodeObject:[NSNumber numberWithInteger:self.age] forKey:@"age"]; [aCoder encodeObject:self.photos forKey:@"photos"]; [aCoder encodeObject:self.phoneNumber forKey:@"phoneNumber"]; [aCoder encodeObject:self.face forKey:@"face"]; }
Face Class
Face.h #import <Foundation/Foundation.h> @interface Face : NSObject <NSCoding> @property (nonatomic, strong) NSString *head; //@property (nonatomic, strong) NSString *eyes; //@property (nonatomic, strong) NSString *nose; //@property (nonatomic, strong) NSString *mouth; //@property (nonatomic, strong) NSString *ears; @end Face.m #import "Face.h" @implementation Face - (id)initWithCoder:(NSCoder *)aDecoder { if(self = [super init]) { self.head = [aDecoder decodeObjectForKey:@"head"]; } return self; } - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:self.head forKey:@"head"]; } @end
写入和读取操作 Person *person = [[Person alloc] init]; person.personId = @"123456789"; person.name = @"Hunk"; person.age = 10; person.photos = @[@"a.png", @"b.png", @"c.png"]; person.phoneNumber = @{@"mobile_phone" : @"987654321", @"work" : @"01012345678"}; Face *face = [[Face alloc] init]; face.head = @"Round shape"; person.face = face; NSData *personData0 = [NSKeyedArchiver archivedDataWithRootObject:person]; [[NSUserDefaults standardUserDefaults] setObject:personData0 forKey:@"person"]; [[NSUserDefaults standardUserDefaults] synchronize]; NSData *personData1 = [[NSUserDefaults standardUserDefaults] objectForKey:@"person"]; Person *person1 = [NSKeyedUnarchiver unarchiveObjectWithData:personData1];
NSUserDefaults写入和读取自定义的对象,布布扣,bubuko.com
时间: 2024-10-08 09:47:46