NSUserDefaults
@interface Person : NSObject <NSCoding>
@property (nonatomic, assign) NSInteger ID;
@property (nonatomic, copy) NSString *name;
@end
// 存
NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
[usersetInteger:ID forKey:@”ID”];
[user setObject:name forKey:@”name”];
[user synchronize];
// 取
NSInteger uId = [[[NSUserDefaults standardUserDefaults] integerValueForKey:@”ID”];
NSString* name = [[NSUserDefaults standardUserDefaults] stringForKey:@”name”];
按對象存取
// 存
[user setObject:self forKey:@”user”];
[user synchronize];
// 取
User* u = [userobjectForKey”@”user”];
2.對象歸檔
要使用對象歸檔,對象必須實現NSCoding協議.大部分Object C對象都符合NSCoding協議,也可以在自定義對象中實現NSCoding協議,要實現NSCoding協議,實現兩個方法:
- (void) encodeWithCoder:(NSCoder *)encoder ;
-(void)initWithCoder:(NSCoder *)encoder.
同時,建議對象也同時實現NSCopying協議,該協議允許復制對象,要實現NSCopying協議須實現 -(id)copyWithZone:(NSZone *)zone 方法 。
@interface Person : NSObject <NSCoding>
@property (nonatomic, assign) NSInteger ID;
@property (nonatomic, copy) NSString *name;
@end
@implementation User
// 以下兩個方法一定要實現,不然在調用的時候會crash
- (void)encodeWithCoder:(NSCoder *)aCoder;
{
// 這裡放置需要持久化的屬性
[aCoder encodeObject:[NSNumber numberWithInteger:self.ID] forKey:@”ID”];
[aCoder encodeObject:self.name forKey:@"name"];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [self init])
{
// 這裡務必和encodeWithCoder方法裡面的內容一致,不然會讀不到數據
self.userID = [[aDecoder decodeObjectForKey:@"ID"] integerValue];
self.name = [aDecoder decodeObjectForKey:@"name"];
}
return self;
}
// 使用方法
+ (BOOL)save {
NSError *error = nil;
// 確定存儲路徑,一般是Document目錄下的文件
NSString* fileName = [self getFileName];
NSString* filePath = [self getFilePath];
if (![[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:&error]) {
NSLog(@”創建用戶文件目錄失敗”);
return NO;
}
return [NSKeyedArchiver archiveRootObject:self toFile:[fileName:userId]];
}
@end