您不能将您的 plist 写入您需要使用的包中, NSDocumentDirectory
或者NSCachesDirectory
只需复制您的 plist 以捆绑覆盖它。
NSCachesDirectory
注意:了解和https://developer.apple.com/icloud/documentation/data-storage/之间的区别NSDocumentDirectory
将您的 plist 从包复制到文档(在下面的代码缓存中),如果您的包中的 plist 只需要一次,我更喜欢在 appdelegate.m 中使用此代码时- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Names.plist"];
NSString *plistInDocuments=@"Names.plist";
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:plistInDocuments];
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
[[NSFileManager defaultManager] copyItemAtPath:sourcePath
toPath:dataPath
error:&error];
}
NSLog(@"Error description-%@ \n", [error localizedDescription]);
NSLog(@"Error reason-%@", [error localizedFailureReason]);
获取您的文件并覆盖它
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistInDocuments=@"Names.plist";
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:plistInDocuments];
//add object here
NSMutableArray *namesNew = [[NSMutableArray alloc] initWithContentsOfFile:dataPath];
[namesNew addObject:arrayValues];
NSError *error = nil;
if ([myFile writeToFile:dataPath options:NSDataWritingAtomic error:&error]) {
// file saved
} else {
// error writing file
NSLog(@"Unable to write plist to %@. Error: %@", dataPath, error);
}