使用这段代码,我试图从 Templates.plist 文件中获取数据,但我在数组中获取了空值。
//from plist
NSString *path = [[NSBundle mainBundle] pathForResource:@"Templates" ofType:@"plist"];
NSMutableArray *arry=[[NSMutableArray alloc]initWithContentsOfFile:path];
NSLog(@"arrayArray:::: %@", arry);
这是我的 plist 文件:
我还想知道如何向这个 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/