如何将 NSMutableArray 保存到 iPhone 的 plist 中
Posted
技术标签:
【中文标题】如何将 NSMutableArray 保存到 iPhone 的 plist 中【英文标题】:How to Save NSMutableArray into plist in iphone 【发布时间】:2012-02-20 06:15:23 【问题描述】:我是 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"];
【问题讨论】:
【参考方案1】: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];
看看Creating Property Lists Programmatically
【讨论】:
【参考方案2】:查看在文档目录中创建 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 目录中创建的 plist 的路径(通过 Xcode)。
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]
【讨论】:
嗨 Neon,感谢您的及时回复。我使用了相同的代码,它适用于 NSString 值,但不适用于 NSMutableArray 或 NSArray。有什么建议吗??? :(【参考方案3】:您可以使用属性列表(NSPropertyListSerialization 或 writeToFile: 方式)。 但请确保您的数组仅包含有效的属性列表对象(NSString、NSNumber、NSData、NSArray 或 NSDictionary 对象)并且 NSDictionary 仅包含 NSString 键。自定义(复杂)对象必须表示为字典。
或者您应该通过 NSCoding 协议使用归档 http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Archiving/Archiving.html 的方法。 不错的指南在这里http://cocoadevcentral.com/articles/000084.php
【讨论】:
【参考方案4】: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);
【讨论】:
以上是关于如何将 NSMutableArray 保存到 iPhone 的 plist 中的主要内容,如果未能解决你的问题,请参考以下文章
如何将类中存在的 NSMutablearray 保存到文件中?
将 NSMutableArray 保存到 plist [关闭]