2012-02-01 40 views
0

我想坚持一个类的对象(不只是NSString's)。例如,我有这个类:IPhone persist模型

** 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来存储它?我应该怎么做?

+0

看看['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

+0

谢谢!这是序列化对象的标准和推荐的方法。此外,另一种方法(更简单)可以将数据(如果它们足够简单)存储在字典中,如[此链接](http://stackoverflow.com/questions/2502193/writing-nsdictionary-to-plist-in -my-app-bundle)。 – 2012-02-01 09:29:04

回答

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