使用此代码我试图从Templates.plist文件中获取数据,但我在数组中获取空值。
//from plist
NSString *path = [[NSBundle mainBundle] pathForResource:@"Templates" ofType:@"plist"];
NSMutableArray *arry=[[NSMutableArray alloc]initWithContentsOfFile:path];
NSLog(@"arrayArray:::: %@", arry);
这是我的plist文件:
此外,我想知道如何向此plist文件添加更多字符串并从此plist中删除字符串。
答案 0 :(得分:3)
首先你不能写你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];
答案 1 :(得分:2)
-(NSMutableArray *)start1
{
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"Templates.plist"];
if ([[NSFileManager defaultManager] fileExistsAtPath:plistPath]){
plistArr = [NSMutableArray arrayWithContentsOfFile: plistPath];
}
else {
plistArr = [[NSMutableArray alloc] init];
}
return plistArr;
}
- (void)createNewRecordWithName:(NSMutableDictionary *)dict
{
plistArr=[self start1];
[plistArr addObject: dict];
//[dict release];
[self writeProductsToFile:plistArr];
}
- (void)writeProductsToFile:(NSMutableArray *)array1 {
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"Template.plist"];
[array1 writeToFile:plistPath atomically:YES];
}
答案 2 :(得分:0)
要将plist放入可变数组,请使用此类方法:
NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:path];
然后,从数组中添加/删除字符串。要将数组保存回plist,请使用:
[array writeToFile:path atomically:YES];