简体   繁体   English

如何在plist中写入数据?

[英]How to write data in plist?

I have created save.plist in a resource folder. 我已经在资源文件夹中创建了save.plist。 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. 我能够读取该数据,但无法通过代码将其写入相同的save.plist。 By using following code I am trying to write the data but it gets stored within my .app plist. 通过使用以下代码,我试图写入数据,但是数据被存储在我的.app plist中。 The code is here 代码在这里

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. 我想要的是,我要写入的数据应仅写入存储在引用中的save.plist中。 I am new with this concept. 我是这个概念的新手。 So if anyone knows it please help me. 因此,如果有人知道,请帮助我。 Thanks in advance. 提前致谢。 :-) :-)

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. 我不知道我是否理解您的问题,但是如果您想在.app捆绑包中写入.plist,则可能是您做错了什么。 If you want to store preferences, you should consider using NSUserDefaults . 如果要存储首选项,则应考虑使用NSUserDefaults
If you really want to modify a bundled .plist - here is some code: 如果您确实要修改捆绑的.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. Nate Flink指出,已弃用了上面使用的某些NSFileManager方法。 He posted an answer with the replacement methods below: https://stackoverflow.com/a/12428472/100848 他用以下替换方法发布了答案: https : //stackoverflow.com/a/12428472/100848

Updated version of the original awesome example by weichsel (thank you!). weichsel原始示例的更新版本(谢谢!)。 Xcode threw a couple warnings one of which is a deprecated method on NSFileManager. Xcode发出了一些警告,其中之一是NSFileManager上不推荐使用的方法。 Updated here with non-deprecated methods from iOS 5.1 使用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];
    }
}

When you build the app, it will create an executable file "appName.app" and all the files are built in the bundle. 在构建应用程序时,它将创建一个可执行文件“ appName.app”,所有文件都构建在捆绑软件中。 Therefore, you can't access to resource folder when the app is running because all the data is in the bundle(not in folder). 因此,在应用程序运行时,您无法访问资源文件夹,因为所有数据都在捆绑包中(而不是在文件夹中)。

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) 您可以在此处找到临时文件夹: 打开查找器-单击用户名(在PLACES下)-库-应用程序支持-iPhone Simulator-用户-应用程序-(您可以在其中找到所有临时文件夹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". 然后,您只需将文件保存到此filePath,它将出现在名为“ 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》. 为您推荐一本书:《开始iPhone开发-探索iPhone SDK》。 In Chapter 11 you can find what you want. 在第11章中,您可以找到所需的内容。

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. 您可以使用NSSearchPathForDirectoriesInDomains函数为该数据找到更合适的文件夹。 (Such as the @"Documents" folder.) (例如@“ Documents”文件夹。)

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". 来自“可可编程”。

您必须将plist复制到文档目录中...因为您无法保存任何内容而不将其保存到文档文件中....在复制时,它将允许在plist上进行写入/修改

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM