objective-c 如何在plist中写入数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/905542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:36:41  来源:igfitidea点击:

How to write data in plist?

iphoneobjective-ccocoa

提问by Jyotsna

I have created save.plist in a resource folder. I have written some data within that directly (without using coding). I am able to read that data but I'm not able to write through code to the same save.plist. By using following code I am trying to write the data but it gets stored within my .app plist. The code is here

我在资源文件夹中创建了 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"]);

I want that, the data which I want to write should get written into save.plist only which is stored in references. I am new with this concept. So if anyone knows it please help me. Thanks in advance. :-)

我想要那个,我想写的数据应该只写入保存在引用中的 save.plist 。我对这个概念很陌生。所以如果有人知道请帮助我。提前致谢。:-)

回答by Thomas Zoechling

I don't know if I understand your question, but if you want to write into a .plist within your .app bundle you are probably doing something wrong. If you want to store preferences, you should consider using NSUserDefaults.
If you really want to modify a bundled .plist - here is some code:

我不知道我是否理解你的问题,但如果你想在你的 .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]];
    }
}

Update:
Nate Flink pointed out that some of the NSFileManager methods used above are deprecated. He posted an answer with the replacement methods below: https://stackoverflow.com/a/12428472/100848

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

回答by Nate Flink

Updated version of the original awesome example by weichsel (thank you!). Xcode threw a couple warnings one of which is a deprecated method on NSFileManager. Updated here with non-deprecated methods from iOS 5.1

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];
    }
}

回答by Chilly Zhong

When you build the app, it will create an executable file "appName.app" and all the files are built in the bundle. Therefore, you can't access to resource folder when the app is running because all the data is in the bundle(not in folder).

当您构建应用程序时,它会创建一个可执行文件“appName.app”,并且所有文件都构建在包中。因此,您无法在应用程序运行时访问资源文件夹,因为所有数据都在包中(不在文件夹中)。

However, you can access to a temp folder which contains some information of the app. You can find the temp folder here: Open finder--click on your username(under PLACES)--Library--Application Support--iPhone Simulator--User--Applications--(here you can find all the temp folders of your iPhone apps)

但是,您可以访问包含应用程序一些信息的临时文件夹。你可以在这里找到临时文件夹: 打开finder--点击你的用户名(在PLACES下)--Library--Application Support--iPhone Simulator--User--Applications--(在这里你可以找到你的所有临时文件夹iPhone 应用程序)

You can access to this temp folder by:

您可以通过以下方式访问此临时文件夹:


NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

If you name your file save.plist, you can access to it like this:

如果您将文件命名为 save.plist,您可以像这样访问它:

NSString *filePath = [documentsDirectory stringByAppendingString:@"_save.plist"];

Then you just save your file to this filePath and it will appear in the temp folder named "Documents_save.plist".

然后您只需将文件保存到此文件路径,它就会出现在名为“Documents_save.plist”的临时文件夹中。

*Note that the temp folder's name varies every time you run the app.

*请注意,每次运行应用程序时,临时文件夹的名称都会有所不同。

Recommend a book for you: 《Beginning iPhone Development--Exploring the iPhone SDK》. In Chapter 11 you can find what you want.

为您推荐一本书:《Beginning iPhone Development--Exploring the iPhone SDK》。在第 11 章中,您可以找到您想要的内容。

回答by Jon Hess

To summarize some of the other answers:

总结一些其他答案:

You're problem is that you're trying to write the file back into the folder that contains your application. That folder is not writable at runtime. Everything you're doing is fine, you just need to pick a different location to write your file to.

您的问题是您正在尝试将文件写回包含您的应用程序的文件夹。该文件夹在运行时不可写。你所做的一切都很好,你只需要选择一个不同的位置来写入你的文件。

You can use the NSSearchPathForDirectoriesInDomains function to find a more suitable folder for this data. (Such as the @"Documents" folder.)

您可以使用 NSSearchPathForDirectoriesInDomains 函数为该数据找到更合适的文件夹。(例如@“Documents”文件夹。)

回答by Texada

try this:

尝试这个:

-(void)add:(NSRunningApplication *) app { 
   if ([self contains:app]) return; 
   [self.apps addObject:app.localizedName]; 
   [self.apps writeToFile:self.dataFile atomically:YES];
}

from "Cocoa Programming".

来自“可可编程”。

回答by Syed Sami ul Ahbab

you have to copy your plist into document directory... because you cannot save anything without saving into document file....when you copied it will allow to write/modify on plist

你必须将你的 plist 复制到文档目录中......因为你不能在不保存到文档文件的情况下保存任何东西......当你复制它时,它将允许在 plist 上写入/修改