我需要在我的plist中添加项目(organizations.plist) 我的plist按以下方式组织: 我有一个根词典,在这一个,我有其他词典...
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>1</key>
<dict>
<key>Address</key>
<string>Address</string>
<key>City</key>
<string>City</string>
<key>Description</key>
<string>Description</string>
<key>Name</key>
<string>name</string>
<key>Coordonates</key>
<string>40.781208, 35.219622</string>
</dict>
</dict>
</plist>
我尝试通过以下代码添加字典:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"organizations" ofType:@"plist"];
NSMutableDictionary *plist = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
NSMutableDictionary *newItem = [NSMutableDictionary dictionary];
[newItem setValue:@"address" forKey:@"address"];
[newItem setValue:@"City" forKey:@"City"];
[newItem setValue:@"32.067487, 34.785156" forKey:@"Coordonates"];
[newItem setValue:@"Description" forKey:@"Description"];
[newItem setValue:@"Name" forKey:@"Name"];
NSArray * allKeys = [plist allKeys];
int count = [allKeys count] + 1;
NSString *strFromInt = [NSString stringWithFormat:@"%d",count];
[plist setObject:newItem forKey:strFromInt];
[plist writeToFile:filePath atomically:NO];
[plist release];
NSLog([plist description]);
日志很好newItem
已添加,但如果我在xCode中打开organizations.plist文件,我发现没有添加任何内容
答案 0 :(得分:1)
首先在plist file
复制document directory
。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
plistPath = [[paths lastObject] stringByAppendingPathComponent:@"organizations.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]){
NSString *bundle = [[NSBundle mainBundle] pathForResource:@"organizations" ofType:@"plist"];
BOOL sucesss = [[NSFileManager defaultManager] copyItemAtPath:bundle toPath:plistPath error:&error];
if (!sucesss) {
NSLog(@"Exception fail to copyItemAtPath : %@",[error description]);
}
}
然后,当您需要编写文件时,您必须从plist
获取document directory
,然后需要update
。
NSMutableDictionary *plist = [NSMutableDictionary dictionaryWithContentsOfFile: plistPath];
NSMutableDictionary *newItem = [NSMutableDictionary dictionary];
[newItem setValue:@"address" forKey:@"address"];
[newItem setValue:@"City" forKey:@"City"];
[newItem setValue:@"32.067487, 34.785156" forKey:@"Coordonates"];
[newItem setValue:@"Description" forKey:@"Description"];
[newItem setValue:@"Name" forKey:@"Name"];
NSArray * allKeys = [plist allKeys];
int count = [allKeys count] + 1;
NSString *strFromInt = [NSString stringWithFormat:@"%d",count];
[plist setObject:newItem forKey:strFromInt];
[plist writeToFile:filePath atomically:NO];
[plist release];
NSLog([plist description]);