所以我将3个NSStrings从3个UITextFields保存到属性列表中。这样可以正常工作,但每次我保存新内容时,应用程序都会覆盖之前保存的数据。所以基本上只使用了一个词典,但我希望应用程序每次保存新内容时创建一个新词典,这样就不会删除任何数据。我不知道我怎么能这样做,所以请帮助我! :)
代码:
NSMutableArray *array = [NSMutableArray arrayWithCapacity:3];
NSArray *keys = [NSArray arrayWithObjects:@"1",@"2",@"3", nil];
[array addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithFormat:@"%@",lab.text],[NSString stringWithFormat:@"%@",lab1.text],[NSString stringWithFormat:@"%@",lab2.text], nil] forKeys:keys]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
[array writeToFile:path atomically:YES];
答案 0 :(得分:0)
使用NSMutableArray添加每个新词典对象,然后将该数组写入data.plist。
答案 1 :(得分:0)
你有没有理由为数组分配容量?我只想使用[[NSMutableArray alloc] init]
,然后添加你的对象。
另外,我在NSMutableDictionaries
中保存NSUserDefaults
时遇到问题,所以我最后做的只是将字典保存到文件中
[dict writeToFile:filePath atomically:NO];
和initWithContentsOfFile
或initWithContentsOfURL
取决于我是否要加载本地或Internet文件。
我应该补充一下,你也可以为NSMutableArray编写ToTile,initWithContentsOf *。
答案 2 :(得分:0)
好的我已经知道了:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
NSLog(@"path='%@'",path);
NSFileManager *nfm = [[NSFileManager alloc] init];
if([nfm fileExistsAtPath:path])
{
// if file exists, get its contents, add more entries and write back
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSArray *keys = [NSArray arrayWithObjects:@"4",@"5",@"6",nil];
[array addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithFormat:@"%@",lab.text],[NSString stringWithFormat:@"%@",lab1.text],[NSString stringWithFormat:@"%@",lab2.text], nil] forKeys:keys]];
NSLog(@"modified array=%@",array);
BOOL ok = [array writeToFile:path atomically:YES];
if(!ok){
NSLog(@"Unable to write appended file");
return;
}
} else {
// if file doesn't exist, create a new one
NSMutableArray *array = [[NSMutableArray alloc] init];
NSArray *keys = [NSArray arrayWithObjects:@"1",@"2",@"3",nil];
[array addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithFormat:@"%@",lab.text],[NSString stringWithFormat:@"%@",lab1.text],[NSString stringWithFormat:@"%@",lab2.text], nil] forKeys:keys]];
NSLog(@"new array=%@",array);
BOOL ok = [array writeToFile:path atomically:YES];
if(!ok){
NSLog(@"Unable to write new file");
return;
}
}