iPhone读/写.plist文件 [英] iPhone read/write .plist file

查看:141
本文介绍了iPhone读/写.plist文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个应用程序,我需要存储用户提供的一些信息。我尝试使用.plist文件存储信息,我发现:

I'm making a application where I need to store some information the user have provided. I try to use a .plist file to store the information, I found this:

NSString *filePath = @"/Users/Denis/Documents/Xcode/iPhone/MLBB/data.plist";
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
[plistDict setValue:@"Man" forKey:@"Gender"];
[plistDict writeToFile:filePath atomically: YES];

问题是只要我在iPhone模拟器中测试它,应用程序才会工作。我已经尝试了这个更改Plist中的数据但没有运气。我还读过一些关于我需要将它添加到我的包中的内容,但是如何?

The problem is that the application will only work as long as I'm testing it in the iPhone simulator. I've tried this Changing Data in a Plist but without luck. I have also read something about that I need to add it to my bundle, but how?

新代码:

- (IBAction)segmentControlChanged{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistLocation = [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:plistLocation];

if (Gender.selectedSegmentIndex == 0) {
    [plistDict setObject:@"Man" forKey:@"Gender"];
    [plistDict writeToFile:plistLocation atomically: YES];
}
else
{
    [plistDict setObject:@"Women" forKey:@"Gender"];
    [plistDict writeToFile:plistLocation atomically: YES];
}
}


推荐答案

我猜你已经将你的plist文件添加到Xcode中的资源文件夹中(我们放置图像,如果没有,那么你需要先放置它)。资源数据默认为 [NSBundle mainBundle] ,iOS不允许我们更改bundle内的数据。首先,您需要将该文件复制到Documents Directory。

I guess you have added your plist file to your resources folder in Xcode (where we place image, if not then you need to place that first). Resources data goes to [NSBundle mainBundle] by default and iOS does not allow us to change data inside bundle. So first you need to copy that file to Documents Directory.

以下是将文件从 NSBundle 复制到Documents目录的代码。

Here is the code for copying file from NSBundle to the Documents directory.

- (NSString *)copyFileToDocumentDirectory:(NSString *)fileName {
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask,
                                                         YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    NSString *documentDirPath = [documentsDir
                                      stringByAppendingPathComponent:fileName];

    NSArray *file = [fileName componentsSeparatedByString:@"."];
    NSString *filePath = [[NSBundle mainBundle]
                                         pathForResource:[file objectAtIndex:0]
                                                  ofType:[file lastObject]];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL success = [fileManager fileExistsAtPath:documentDirPath];

    if (!success) {
        success = [fileManager copyItemAtPath:filePath
                                       toPath:documentDirPath
                                        error:&error];
        if (!success) {
        NSAssert1(0, @"Failed to create writable txt file file with message \
                                         '%@'.", [error localizedDescription]);
        }
    }

    return documentDirPath;
}

现在你可以使用返回的 documentDirPath 访问该文件并对其进行操作(读/写)。

Now you can use the returned documentDirPath to access that file and manipulate (Read/Write) over that.

plist结构为:

<array>
    <dict>key-value data</dict>
    <dict>key-value data</dict>
</array>

以下是将数据写入plist文件的代码:

Here is code to write data into plist file:

/* Code to write into file */

- (void)addToMyPlist {
    // set file manager object
    NSFileManager *manager = [NSFileManager defaultManager];

    // check if file exists
    NSString *plistPath = [self copyFileToDocumentDirectory:
                                                       @"MyPlistFile.plist"];

    BOOL isExist = [manager fileExistsAtPath:plistPath];    
    // BOOL done = NO;

    if (!isExist) {
        // NSLog(@"MyPlistFile.plist does not exist");
        // done = [manager copyItemAtPath:file toPath:fileName error:&error];
    }
    // NSLog(@"done: %d",done);

    // get data from plist file
    NSMutableArray * plistArray = [[NSMutableArray alloc]
                                           initWithContentsOfFile:plistPath];

    // create dictionary using array data and bookmarkKeysArray keys
    NSArray *keysArray = [[NSArray alloc] initWithObjects:@"StudentNo", nil];
    NSArray *valuesArray = [[NSArray alloc] initWithObjects:
                                   [NSString stringWithFormat:@"1234"], nil];

    NSDictionary plistDict = [[NSDictionary alloc]
                                                  initWithObjects:valuesArray
                                                          forKeys:keysArray];

    [plistArray insertObject:poDict atIndex:0];

    // write data to  plist file
    //BOOL isWritten = [plistArray writeToFile:plistPath atomically:YES];
    [plistArray writeToFile:plistPath atomically:YES];

    plistArray = nil;

    // check for status
    // NSLog(@" \n  written == %d",isWritten);
}

这篇关于iPhone读/写.plist文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆