将NSmutableArray保存到文件并加载

时间:2010-06-19 17:56:55

标签: objective-c serialization nsmutablearray

我为我的iphone写了应用程序,我想将一些NSmutablearray保存到文件中 然后加载它。我读过有关NSArchiver的内容,但不明白如何使用 我的主意是:

@interface Shop : NSObject 
{    
    NSString       *m_Name;
    NSString       *m_Description;
    NSString       *m_Category;
    NSString       *m_BestSaleDesc;
    NSString       *m_AdditionalInfo;   
    NSInteger       m_ShopId;
    NSInteger       m_ChainId;
    NSMutableArray *m_SalesList;
    NSData         *m_Icon;
    bool            m_Filtered;
    bool            m_Deleted;
    bool            m_Hidden;
}

有人可以给我一些示例代码,说明如何将calss Shop的NSmutableArray保存到文件名ShopFile.sav,然后再将其重新加载到NSmutableArray对象。
非常感谢

2 个答案:

答案 0 :(得分:7)

编辑:重写整件事。
保存:

NSMutableDictionary *saveDict = [NSMutableDictionary dictionary];
[saveDict setValue:m_Name forKey:@"m_Name"];
[saveDict setValue:m_Description forKey:@"m_Description"];
[saveDict setValue:m_Category forKey:@"m_Category"];
[saveDict setValue:m_BestSaleDesc forKey:@"m_BestSaleDesc"];
[saveDict setValue:m_AdditionalInfo forKey:@"m_AdditionalInfo"];
[saveDict setValue:[NSNumber numberWithInt:m_ShopId] forKey:@"m_ShopId"];
[saveDict setValue:[NSNumber numberWithInt:m_ChainId] forKey:@"m_ChainId"];
[saveDict setValue:m_SalesList forKey:@"m_SalesList"];
[saveDict setValue:m_Icon forKey:@"m_Icon"];
[saveDict setValue:[NSNumber numberWithBool:m_Filtered] forKey:@"m_Filtered"];
[saveDict setValue:[NSNumber numberWithBool:m_Deleted] forKey:@"m_Deleted"];
[saveDict setValue:[NSNumber numberWithBool:m_Hidden] forKey:@"m_Hidden"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingString:@"/ShopFile.sav"];
[saveDict writeToFile:filePath atomically:YES];

装载:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingString:@"/ShopFile.sav"];
NSDictionary *loadDict = [NSDictionary dictionaryWithContentsOfFile:filePath];
m_Name =            [loadDict valueForKey:@"m_Name"];
m_Description =     [loadDict valueForKey:@"m_Description"];
m_Category =        [loadDict valueForKey:@"m_Category"];
m_BestSaleDesc =    [loadDict valueForKey:@"m_BestSaleDesc"];
m_AdditionalInfo =  [loadDict valueForKey:@"m_AdditionalInfo"];
m_ShopId =         [[loadDict valueForKey:@"m_ShopId"] intValue];
m_ChainID =        [[loadDict valueForKey:@"m_ChainId"] intValue];
m_SalesList =       [loadDict valueForKey:@"m_SalesList"];
m_Icon =            [loadDict valueForKey:@"m_Icon"];
m_Filtered =       [[loadDict valueForKey:@"m_Filtered"] boolValue];
m_Deleted =        [[loadDict valueForKey:@"m_Deleted"] boolValue];
m_Hidden =         [[loadDict valueForKey:@"m_Hidden"] boolValue];

应该更好地工作;)

答案 1 :(得分:0)

为什么不使用核心数据? Core Data