我已经在一个资源文件夹中创建了save.plist。我已经在其中直接写了一些数据(不使用编码)。我可以读取这些数据,但不能通过代码将其写入相同的save.plist。通过使用下面的代码,我试图写入数据,但它被存储在我的.app plist中。代码在这里
NSString *errorDesc = nil;
NSPropertyListFormat format;
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"save" ofType:@"plist"];
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSMutableDictionary *temp = (NSMutableDictionary *)[NSPropertyListSerialization
propertyListFromData:plistXML
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format errorDescription:&errorDesc];
if (!temp) {
NSLog(errorDesc);
[errorDesc release];
}
// [temp setValue:@"123" forKey:@"line1"];
// [temp writeToFile:plistPath atomically: YES];
//Reading data from save.plist
NSLog([temp objectForKey:@"name"]);
NSLog([temp objectForKey:@"wish"]);
NSNumber *num=[temp valueForKey:@"roll"];
int i=[num intValue];
printf("%d",i);
//writitng the data in save.plist
[temp setValue:@"green" forKey:@"color"];
[temp writeToFile:plistPath atomically: NO];
NSMutableDictionary *temp1 = (NSMutableDictionary *)[NSPropertyListSerialization
propertyListFromData:plistXML
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format errorDescription:&errorDesc];
NSLog([temp objectForKey:@"color"]);
我想要的是,我想要写的数据应该只被写入到save.plist中,它存储在引用中。我对这个概念还很陌生。因此,如果有人知道它,请帮助我。提前谢谢。:-)
发布于 2012-09-15 00:27:59
weichsel的原始令人敬畏的示例的更新版本(谢谢!)Xcode抛出了几个警告,其中之一是NSFileManager上的一个不推荐使用的方法。此处更新了iOS 5.1中未弃用的方法
NSString *plistPath = nil;
NSFileManager *manager = [NSFileManager defaultManager];
if ((plistPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"mySpecial/PathTo.plist"]))
{
if ([manager isWritableFileAtPath:plistPath])
{
NSMutableDictionary *infoDict = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
[infoDict setObject:@"foo object" forKey:@"fookey"];
[infoDict writeToFile:plistPath atomically:NO];
[manager setAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate] ofItemAtPath:[[NSBundle mainBundle] bundlePath] error:nil];
}
}
发布于 2009-05-25 23:14:26
总结一下其他一些答案:
您的问题是您试图将文件写回包含您的应用程序的文件夹。该文件夹在运行时不可写。你所做的一切都很好,你只需要选择一个不同的位置来写入你的文件。
您可以使用NSSearchPathForDirectoriesInDomains函数为这些数据查找更合适的文件夹。(例如@"Documents“文件夹。)
发布于 2011-04-01 23:23:55
试试这个:
-(void)add:(NSRunningApplication *) app {
if ([self contains:app]) return;
[self.apps addObject:app.localizedName];
[self.apps writeToFile:self.dataFile atomically:YES];
}
来自"Cocoa Programming“。
https://stackoverflow.com/questions/905542
复制相似问题