iPhone - 无法将数据保存到iPhone上

时间:2011-09-25 17:18:42

标签: iphone objective-c ios xcode

我正在尝试将数组保存到我的iphone上的.plist文件中,但它不会保存到它。当我在模拟器上尝试它时,它的工作原理。但是当我在iPhone上运行它时它不起作用。我检查设备上是否存在该文件,它确实存在,我可以从文件中读取数据,但不会写入该文件。这是我将数据添加到.plist文件时的代码。

//Sorts the arrays
    [self sortArrays];

    NSString *sString = [[NSString alloc] initWithFormat:@"Schema%i", currentIndex];
    NSString *daPath = [[NSBundle mainBundle] pathForResource:sString ofType:@"plist"];
    NSLog(@"Path: %@", daPath);

    //Checks if the file exists
    BOOL exists;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    exists = [fileManager fileExistsAtPath:daPath];
    if(!exists)
        NSLog(@"PATH %@ DOES NOT EXIST", daPath);
    else
        NSLog(@"PATH %@ DO EXIST!!", daPath);

    //Writes out the array to check if it gots any elements
    for (int i = 0; i < [itemsArray count]; i++)
        NSLog(@"%i: %@", i, [(NSMutableArray*)[itemsArray objectAtIndex:i] objectAtIndex:0]);

    //Writes the array to the .plist
    [itemsArray writeToFile:daPath atomically:YES];

    //Gets the .plist file
    NSMutableArray *tmpA2 = [[NSMutableArray alloc] initWithContentsOfFile:daPath];

    //Checks if the new elements that got added is there.
    for (int i = 0; i < [tmpA2 count]; i++)
        NSLog(@"FILE: %i: %@", i, [(NSMutableArray*)[tmpA2 objectAtIndex:i] objectAtIndex:0]);

    [sString release];
    [itemsArray release];
    sString = nil;
    itemsArray = nil;

//Sorts the arrays [self sortArrays]; NSString *sString = [[NSString alloc] initWithFormat:@"Schema%i", currentIndex]; NSString *daPath = [[NSBundle mainBundle] pathForResource:sString ofType:@"plist"]; NSLog(@"Path: %@", daPath); //Checks if the file exists BOOL exists; NSFileManager *fileManager = [NSFileManager defaultManager]; exists = [fileManager fileExistsAtPath:daPath]; if(!exists) NSLog(@"PATH %@ DOES NOT EXIST", daPath); else NSLog(@"PATH %@ DO EXIST!!", daPath); //Writes out the array to check if it gots any elements for (int i = 0; i < [itemsArray count]; i++) NSLog(@"%i: %@", i, [(NSMutableArray*)[itemsArray objectAtIndex:i] objectAtIndex:0]); //Writes the array to the .plist [itemsArray writeToFile:daPath atomically:YES]; //Gets the .plist file NSMutableArray *tmpA2 = [[NSMutableArray alloc] initWithContentsOfFile:daPath]; //Checks if the new elements that got added is there. for (int i = 0; i < [tmpA2 count]; i++) NSLog(@"FILE: %i: %@", i, [(NSMutableArray*)[tmpA2 objectAtIndex:i] objectAtIndex:0]); [sString release]; [itemsArray release]; sString = nil; itemsArray = nil;

有谁知道为什么它不起作用?

1 个答案:

答案 0 :(得分:1)

您无法写入应用程序包,您需要写入应用程序的文档目录。

NSString *fileName = @"fileName";
NSArray *searchPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectoryPath = [searchPath objectAtIndex:0];
NSString *filePath = [documentDirectoryPath stringByAppendingPathComponent:fileName]; 

如果启动时应用程序包中的文件中有初始数据,则将其复制到文档目录(如果该文件目录不存在),然后可以对其进行读取,修改和写入。