您使用 Xcode 接口创建的 .plist 可读但不可写。如果您想更改项目 Bundle 中的文件,主要是在 Documents 或 Library 中的一个文件夹中进行复制,然后总是需要处理副本或使用代码创建 .plist。
创建:
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* plistPath = [documentsPath stringByAppendingPathComponent:@"test.plist"];
NSArray* fruits= [NSArray arrayWithObjects:@"apple", @"orange", @"cherry", nil];
NSArray* vegetables= [NSArray arrayWithObjects:@"cabbage", @"pumpkin", @"leek", nil];
NSDictionary* dictionary= [NSDictionary dictionaryWithObjectsAndKeys:fruits, @"fruits", vegetables, @"vegetables", nil];
[dictionary writeToFile:plistPath atomically:YES];
读写:
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* plistPath = [documentsPath stringByAppendingPathComponent:@"test.plist"];
NSDictionary* dictionary= [[NSDictionary alloc] plistPath ];
NSMutableArray* fruits= [dictionary objectForKey:@"fruits"];
NSMutableArray* vegetables= [dictionary objectForKey:@"vegetables"];
NSLog(@"First Fruit: %@",[fruits objectAtIndex:0]);
NSLog(@"First Vegetable: %@",[vegetables objectAtIndex:0]);
[fruits replaceObjectAtIndex:0 withObject:@"banana"];
[dictionary writeToFile:plistYolu atomically:YES];