使用NSCoding:
在News.m,我说:
- (void) encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:atrib1 forKey:@"key1"];
[encoder encodeObject:atrib2 forKey:@"key2"];
}
- (id)initWithCoder:(NSCoder *)decoder {
self = [super init];
atrib1 = [[decoder decodeObjectForKey:@"key1"] retain];
atrib2 = [[decoder decodeObjectForKey:@"key2"] retain];
return self;
}
-(void)dealloc{
[super dealloc];
[atrib1 release];
[atrib2 release];
}
在News.h:
@interface News : NSObject<NSCoding>{
NSCoder *coder;
}
@property (nonatomic, retain) NSString * atrib1;
@property (nonatomic, retain) NSString * atrib2;
@end
要阅读更新,并在plist中坚持一个新的对象:
- (IBAction)addANewNews:(id)sender {
//Plist File
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *plistPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"myplist.plist"];
//Reading current news
NSData *oldNews = [NSData dataWithContentsOfFile:plistPath];
NSMutableArray *news = (NSMutableArray *)[NSKeyedUnarchiver unarchiveObjectWithData:oldNews];
if (news == nil)
news = [[NSMutableArray alloc] init];
//Adding a new news
[news addObject:aNewNews];
NSError *error;
NSData* newData = [NSKeyedArchiver archivedDataWithRootObject:news];
//persisting the updated news
BOOL success =[newData writeToFile:plistPath options:NSDataWritingAtomic error:&error];
if (!success) {
NSLog(@"Could not write file.");
}else{
NSLog(@"Success");
}
}
看看['NSCoding'](http:// d eveloper.apple.com/library/iOS/#documentation/Cocoa/Reference/Foundation/Protocols/NSCoding_Protocol/Reference/Reference.html) – rckoenes 2012-02-01 08:59:04
谢谢!这是序列化对象的标准和推荐的方法。此外,另一种方法(更简单)可以将数据(如果它们足够简单)存储在字典中,如[此链接](http://stackoverflow.com/questions/2502193/writing-nsdictionary-to-plist-in -my-app-bundle)。 – 2012-02-01 09:29:04