我是Objective-C编程的新手,我正在尝试将一个新的字典对象写入一个包含字典数组的plist,以持久保存数据。
我的plist结构是:
<plist>
<array>
<dict>
<key>toyName</key>
<string>N64</string>
<key>toyBrand</key>
<string>Nintendo</string>
</dict>
</array>
</plist>
我尝试编写新字典的功能:
-(void)saveData {
NSFileManager *fm = [NSFileManager new];
NSError *err = nil;
NSURL *docsurl = [fm URLForDirectory:NSDocumentDirectory
inDomain:NSUserDomainMask
appropriateForURL:nil
create:YES
error:&err];
NSURL *url = [docsurl URLByAppendingPathComponent:@"Toy.plist"];
NSMutableArray *plistData = [NSMutableArray arrayWithContentsOfURL:url];
NSMutableDictionary *newDict = [[NSMutableDictionary alloc]init];
NSDate * now = [NSDate date];
[newDict setValue:itemText.text forKey:@"toyName"];
[newDict setValue:brandText.text forKey:@"toyBrand"];
[plistData addObject:newDict];
}
调用saveData函数时,使用NSLog打印时plistData数组仍然相同,并且plist并未更改。如何将新的字典对象写入包含字典数组的plist?
答案 0 :(得分:0)
在[plistData writeToURL:url atomically:YES]
下有[plistData addObject:newDict]
的代码,但是必须确保plistData不是nil,而是通过url查找相应的文件。
例如:
-(void)saveData {
NSFileManager *fm = [NSFileManager new];
NSError *err = nil;
NSURL *docsurl = [fm URLForDirectory:NSDocumentDirectory
inDomain:NSUserDomainMask
appropriateForURL:nil
create:YES
error:&err];
NSURL *url = [docsurl URLByAppendingPathComponent:@"Toy.plist"];
NSMutableArray *plistData = [NSMutableArray arrayWithContentsOfURL:url];
NSMutableDictionary *newDict = [[NSMutableDictionary alloc]init];
NSDate * now = [NSDate date];
[newDict setValue:itemText.text forKey:@"toyName"];
[newDict setValue:brandText.text forKey:@"toyBrand"];
[plistData addObject:newDict];
}