如何在iPhone中将NSMutableArray保存到plist文件

5

我是一个iPhone新手,我想将NSMutableArray数据保存到plist文件中,我的代码如下:

NSArray *array = [[NSArray alloc] initWithArray:self.artistDetailsArray];
[self.artistDetailsArray writeToFile:self.path atomically:YES];

但是在我的plist路径中显示0个元素。请帮助我。谢谢提前:
以下是我的代码,用于将数据存储到plist和NSUserDefault中。 对于NSMutableArray / NSArray,它们都无法正常工作,但对于NSString,则可以正常工作。是否有最大大小限制可以存储在plist或UserDefault中? NSMutableArray仅包含文本/一组NSDictionary。请给我建议。
- (void)initialiseDataFromLocalStorage
{
       NSFileManager *fileManager = [NSFileManager defaultManager];
       NSError *error;
       NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
       NSString *documentsDirectory = [paths objectAtIndex:0];
       self.path = [documentsDirectory stringByAppendingPathComponent:@"saveLogin.plist"];
       if ([fileManager fileExistsAtPath:self.path] == NO) {
               NSString *pathToDefaultPlist = [[NSBundle mainBundle] pathForResource:@"saveLogin" ofType:@"plist"];
               if ([fileManager copyItemAtPath:pathToDefaultPlist toPath:self.path error:&error] == NO) {
                       NSAssert1(0,@"Failed with error '%@'.", [error localizedDescription]);
               }
       }

   // To get stored value from .plist
       NSDictionary *dict = [[NSDictionary alloc]initWithContentsOfFile:self.path];
       self.ResumedataDictionary = [[NSMutableDictionary alloc]initWithDictionary:dict];
       [dict release];
   self.artistDetailsArray = [[NSMutableArray alloc] initWithArray:[self.ResumedataDictionary objectForKey:@"artistDetailsDict"]];    
   // To get stored value from NSUserDefault
   NSUserDefaults *fetchData = [NSUserDefaults standardUserDefaults];
   self.artistDetailsArray = [fetchData objectForKey:@"artistDetailsDict"];    
}        

-(void)saveDataToLocalStorage
{    
   // To store value into .plist
   NSArray *array = [[NSArray alloc] initWithArray:self.artistDetailsArray];
   [ResumedataDictionary setObject:array forKey:@"artistDetailsDict"];
       [ResumedataDictionary writeToFile:self.path atomically:YES];  

   // To store value into NSUserDefault
   NSUserDefaults *fetchData = [NSUserDefaults standardUserDefaults];
   [fetchData setObject:self.artistDetailsArray forKey:@"artistDetailsDict"];    
}
4个回答

5
NSMutableArray *array=[[NSMutableArray alloc] init];
    [array addObject:@"test"];
    [array writeToFile:@"/Users/parag/test.plist" atomically:YES];
    [array release];

或者
NSMutableArray *array=[[NSMutableArray alloc] init];
[array addObject:@"test121"];
id plist = [NSPropertyListSerialization dataFromPropertyList:(id)array                            format:NSPropertyListXMLFormat_v1_0 errorDescription:@error];


 [plist writeToFile:@"/Users/parag/test.plist" atomically:YES];

请查看编程创建属性列表


4

看一下这段代码,它创建了指向文档目录中plist文件的路径:

NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"]; //3

NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath: path]) //4
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:@”data” ofType:@”plist”]; //5

[fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
}

1) 创建路径列表。

2) 从列表中获取到您的文档目录路径。

3) 创建一个完整的文件路径。

4) 检查文件是否存在。

5) 获取到之前在 bundle 目录中由 Xcode 创建的 plist 文件路径。

6) 将该 plist 文件复制到您的文档目录中。

接下来,读取数据:

NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

//load from savedStock example int value
int value;
value = [[savedStock objectForKey:@"value"] intValue];

[savedStock release];

写入数据:

NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];

//here add elements to data file and write data to file
int value = 5;

[data setObject:[NSNumber numberWithInt:value] forKey:@”value”];

[data writeToFile: path atomically:YES];
[data release]

1
嗨Neon, 感谢您的快速回复。我使用了相同的代码,它可以处理NSString类型的值,但无法处理NSMutableArray或NSArray。有什么建议吗? :( - iPhone4s

3
你可以使用属性列表(NSPropertyListSerialization或writeToFile:方法)。但是请确保你的数组只包含有效的属性列表对象(NSString、NSNumber、NSData、NSArray或NSDictionary对象),并且NSDictionary只有NSString键。自定义(复杂)对象必须表示为字典。
或者,你可以通过NSCoding协议使用归档方法。这里有一个不错的指南http://cocoadevcentral.com/articles/000084.php,Cocoa框架文档中也有相关介绍http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Archiving/Archiving.html

0
NSData *serializedData;
        NSString *error;
        serializedData = [NSPropertyListSerialization dataFromPropertyList:YourArray(You can use dictionaries.strings..and others too)
        format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
        if (serializedData) {
        // Serialization was successful, write the data to the file system // Get an array of paths.

       NSArray *documentDirectoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docDir = [NSString stringWithFormat:@”%@/serialized.xml”,
         [documentDirectoryPath objectAtIndex:0]];
        [serializedData writeToFile:docDir atomically:YES];
 }
        else {
        // An error has occurred, log it
        NSLog(@”Error: %@”,error); }
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接