2013-03-27 121 views
1

如何存儲自定義對象NSMutableArray? 我有加載和保存文件的代碼:ios存儲自定義對象

- (NSMutableArray *)loadDataFromFile:(NSString *)fileName { 
    NSError *error; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *docDir = [paths objectAtIndex:0]; 
    NSString *path = [docDir stringByAppendingPathComponent:fileName]; 
    NSFileManager *fileMgr = [NSFileManager defaultManager]; 
    if (![fileMgr fileExistsAtPath:path]) { 
     NSArray *fileArray = [fileName componentsSeparatedByString:@"."]; 
     NSString *name = [fileArray objectAtIndex:0]; 
     NSString *ext = [fileArray objectAtIndex:1]; 
     NSString *bundle = [[NSBundle mainBundle] pathForResource:name ofType:ext]; 
     [fileMgr copyItemAtPath:bundle toPath:path error:&error]; 
    } 
    NSMutableArray *data = [[NSMutableArray alloc] initWithContentsOfFile:path]; 
    return data; 
} 

- (void)saveData:(NSMutableArray *)arrayData toFile:(NSString *)filename forKey:(NSString *)key { 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *docDir = [paths objectAtIndex:0]; 
    NSString *path = [docDir stringByAppendingPathComponent:filename]; 
    [arrayData writeToFile: path atomically:YES]; 
    NSLog(@"%@", arrayData); 
} 

但是,當我用data.plist作爲文件名,它沒有工作,因爲NSLog(@"%@", arrayData);返回列表自定義對象不會忽略:

「AreaTableRecord:0x76a7ef0」

此自定義對象使用此代碼插入陣列

我該如何存儲NSMutableArrayself.areas包含自定義對象AreaTableRecord? 和 什麼文件格式shloud我用來存儲這些數據? (在我看來,plist不起作用)

回答

1

您只能將原始數據類型存儲在NSDefaults或plist中。爲了解決這個問題,您可以選擇將信息存儲在數據庫中....或將對象編碼爲字節流,然後將其保存到文件中。

看看這個thread。它詳細介紹瞭如何編碼你的對象。

基本上你需要將這些方法添加到您的自定義類:

- (void)encodeWithCoder:(NSCoder *)encoder 
{ 
     //Encode properties, other class variables, etc 
    [encoder encodeObject:self.question forKey:@\"question\"]; 
    [encoder encodeObject:self.categoryName forKey:@\"category\"]; 
    [encoder encodeObject:self.subCategoryName forKey:@\"subcategory\"]; 
} 


- (id)initWithCoder:(NSCoder *)decoder 
{ 
    self = [super init]; 
    if(self != nil) 
    { 
       //decode properties, other class vars 
     self.question = [decoder decodeObjectForKey:@\"question\"]; 
     self.categoryName = [decoder decodeObjectForKey:@\"category\"]; 
     self.subCategoryName = [decoder decodeObjectForKey:@\"subcategory\"]; 
    } 
    return self; 
} 

然後才能使用它們,你撥打電話是這樣的:

有關設置:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 
NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:obj]; 
[defaults setObject:myEncodedObject forKey:@\"myEncodedObjectKey\"]; 

檢索:

NSUserDefaults defaults = [NSUserDefaults standardUserDefaults]; 
NSData *myEncodedObject = [defaults objectForKey: key]; 
MyCustomObject* obj = (MyCustomObject*)[NSKeyedUnarchiver unarchiveObjectWithData: myEncodedObject]; 
+0

thx男人你救了我的命:D – 2013-03-29 02:06:59

+0

一個慷慨的答案!費裏,給他投票! :) – Fattie 2014-08-01 11:03:50

相關問題