iPhone读/写.plist文件

时间:2012-02-17 21:12:51

标签: iphone xcode plist

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

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模拟器中测试应用程序,该应用程序才会起作用。我试过这个Changing Data in a Plist,但没有运气。我还读过一些关于我需要将它添加到我的包中的内容,但是如何?

新代码:

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

2 个答案:

答案 0 :(得分:14)

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

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

- (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来访问该文件并对其进行操作(读/写)。

plist结构是:

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

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

/* 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);
}

答案 1 :(得分:8)

您是否在设备上使用相同的路径?设备上的应用程序是沙箱,只能读取/写入其文档目录中的文件。抓住该文件路径like this并附加您的plist名称。这种方法也适用于模拟器。

试试这个:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistLocation = [documentsDirectory stringByAppendingPathComponent:@"myplist.plist"];