gpt4 book ai didi

iphone - 如何在plist中写入数据?

转载 作者:太空狗 更新时间:2023-10-30 03:16:20 25 4
gpt4 key购买 nike

我在资源文件夹中创建了 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 中。我对这个概念很陌生。所以如果有人知道请帮助我。提前致谢。:-)

最佳答案

我不知道我是否理解你的问题,但如果你想写入你的 .app 包中的 .plist,你可能做错了什么。如果你想存储偏好,你应该考虑使用 NSUserDefaults .
如果你真的想修改一个捆绑的 .plist - 这里有一些代码:

NSString *plistPath = nil;
NSFileManager *manager = [NSFileManager defaultManager];
if (plistPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"Contents/Info.plist"])
{
if ([manager isWritableFileAtPath:plistPath])
{
NSMutableDictionary *infoDict = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath];
[infoDict setObject:[NSNumber numberWithBool:hidden] forKey:@"LSUIElement"];
[infoDict writeToFile:plistPath atomically:NO];
[manager changeFileAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate] atPath: [[NSBundle mainBundle] bundlePath]];
}
}

更新:
Nate Flink 指出上面使用的一些 NSFileManager 方法已被弃用。他用下面的替换方法发布了一个答案: https://stackoverflow.com/a/12428472/100848

关于iphone - 如何在plist中写入数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/905542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com