NSUserDefaults
用於用戶偏好,不存儲應用程序數據。使用CoreData或將對象序列化到文檔目錄中。你需要讓你的班級實施NSCoding
協議才能工作。
1)Occasion.h
@interface Occasion : NSObject <NSCoding>
2實施NSCoding
)在Occasion.m
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
self.title = [aDecoder decodeObjectForKey:@"title"];
self.date = [aDecoder decodeObjectForKey:@"date"];
self.imagePath = [aDecoder decodeObjectForKey:@"imagePath"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:title forKey:@"title"];
[aCoder encodeObject:date forKey:@"date"];
[aCoder encodeObject:imagePath forKey:@"imagePath"];
}
3實現協議)存檔在文件目錄中的數據以一個文件
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *path= [documentsPath stringByAppendingPathComponent:@「occasions」];
[NSKeyedArchiver archiveRootObject:occasions toFile:path];
4 )要取消存檔...
NSMutableArray *occasions = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
感謝您的幫助。這個想法現在對我來說很清楚。最後一個問題:對於這個步驟(NSArray * myArray = [NSKeyedUnarchiver unarchiveObjectWithData:serialized];)會給我一個NSArray,而我的原始數組是一個NSMutableArray。所以我應該使用類似[複製可變]的東西? – Ali
如果它返回一個標準的'NSArray',然後使用'[array mutableCopy]'得到一個可變的版本。 –
再次感謝您的幫助。 – Ali