iPhone坚持模型

时间:2012-02-01 08:28:56

标签: iphone persistence plist

我想坚持一个类的对象(不仅仅是NSString)。例如,我有这个课程:

** News.h:**

    #import <Foundation/Foundation.h>
    @interface News : NSObject
    @property (nonatomic, retain) NSString * atrib1;
    @property (nonatomic, retain) NSString * atrib2;
    @end

** News.m:**

    #import "News.h"
    @implementation News
    @synthesize atrib1;
    @synthesize atrib2;
    @end

我是否应该使用plist存储它?我该怎么办?

1 个答案:

答案 0 :(得分:0)

使用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");
}
}