ios - 从 plist 获取数据到 NSMutableArray 并将 NSMutableArray 写入同一个 plist iPhone

标签 ios objective-c iphone plist read-write

使用这段代码,我试图从 Templates.plist 文件中获取数据,但我在数组中获取了空值。

//from plist
NSString *path = [[NSBundle mainBundle] pathForResource:@"Templates" ofType:@"plist"];
NSMutableArray *arry=[[NSMutableArray alloc]initWithContentsOfFile:path];

NSLog(@"arrayArray:::: %@", arry);

这是我的 plist 文件:

Plist file

我还想知道如何向这个 plist 文件添加更多字符串并从这个 plist 中删除一个字符串。

最佳答案

首先,您不能在 mainBundle 中写入任何内容。要写入 plist,您需要将其复制到文档目录。这是这样做的:

- (void)createEditableCopyOfIfNeeded 
{
     // First, test for existence.
     BOOL success;

     NSFileManager *fileManager = [NSFileManager defaultManager];
     NSError *error;
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
     NSString *documentsDirectory = [paths objectAtIndex:0];
     NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"Template.plist"];
     success = [fileManager fileExistsAtPath:writablePath];

     if (success) 
         return;

     // The writable file does not exist, so copy from the bundle to the appropriate location.
     NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Template.plist"];
     success = [fileManager copyItemAtPath:defaultPath toPath:writablePath error:&error];
     if (!success) 
         NSAssert1(0, @"Failed to create writable file with message '%@'.", [error localizedDescription]);
}

因此调用此函数将检查文件是否存在于文档目录中。如果没有,它会将文件复制到文档目录。如果文件存在,它就返回。接下来,您只需要访问该文件即可对其进行读写。要访问您只需要文档目录的路径并将您的文件名添加为路径组件。

NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [docDir stringByAppendingPathComponent:@"Template.plist"];

从plist中获取数据:

NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:filePath];

将文件写回文档目录。

    [array writeToFile:filePath atomically: YES];

关于ios - 从 plist 获取数据到 NSMutableArray 并将 NSMutableArray 写入同一个 plist iPhone,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9193363/

相关文章:

iphone - 如何检查两个 ImageView 是否处于同一位置?

iphone - 如何在同一个 UITextField 或 UITextView 中保留两种不同的字体?

html - "Ok"按钮未出现在 Ionic App 的 <select> 标签中

ios - 使用swift在ios上同时播放音频和振动

ios - 滚动内部 UITableView 时处理 NSNotification

ios - obj_msgSend CPU 使用率 100%

iphone - 传递一段代码?

iphone - 如何隐藏 iOS 数字键盘

ios - 与 UIPageControl 一起使用时, Collection View 高度不正确

objective-c - sizeWithFont 在 UITextField 中返回错误的高度