【问题标题】:iPhone Dev - Edit objects in Array from PlistiPhone Dev - 从 Plist 编辑数组中的对象
【发布时间】:2012-09-18 12:24:09
【问题描述】:

我有一个 Plist,其中有许多 Array。在这些数组中是我正在读取的不同对象,但是我在编辑数组中的这些对象然后再次将数组保存回 Plist 文件时陷入困境。

我已经像这样读取文件了...

Array = [myArrays objectAtIndex:arrayCounter]; //This tells it which Array to load.

myObject = [Array objectAtIndex:0]; //This reads that object in the array. (This is what I want to edit.)

我想知道如何编辑该对象(它是一个字符串),然后将其保存回数组中,然后将该数组保存回存储它的 Plist 文件中。

提前致谢!

P.S - 如果需要,我愿意发布更多代码或信息。

【问题讨论】:

    标签: iphone arrays object plist save


    【解决方案1】:

    您不能将数据保存在应用程序的主包中,而必须像这样在文档目录中进行:

     NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *plistFilePath = [documentsDirectory stringByAppendingPathComponent:@"Data.plist"];
    
    if([[NSFileManager defaultManager] fileExistsAtPAth:plistFilePath]) 
    {//plist already exits in doc dir so save content in it
    
     NSMutableArray *data = [NSMutableArray arrayWithContentsOfFile:plistFilePath];
     NSArray *arrValue = [data objectAtIndex:arrayCounter];
    
     NSString *strValue = [arrValue objectAtIndex:0];
     strValue = [strValue stringByAppending:@"hello"]; //change your value here
    
     [[data objectAtIndex:arrayCounter] replaceObjectAtIndex:0 withObject:strValue]; //value replaced
     [data writeToFile:plistFilePath atomically:YES];
    }
    else{ //firstly take content from plist and then write file document directory. it will be executed only once
    
     NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
     NSMutableArray *data = [NSMutableArray arrayWithContentsOfFile:plistPath];
     NSArray *arrValue = [data objectAtIndex:arrayCounter];
    
     NSString *strValue = [arrValue objectAtIndex:0];
     strValue = [strValue stringByAppending:@"hello"]; //change your value here
    
     [[data objectAtIndex:arrayCounter] replaceObjectAtIndex:0 withObject:strValue]; //value replaced
     [data writeToFile:plistFilePath atomically:YES];
    
    }
    

    【讨论】:

    • 我的 Plist 文件在我的支持文件夹中,你是说我必须将所有这些文件保存到 iPhone 的文档目录中?
    • 是的,我将保存在 doc 目录中,因为您无法更新应用程序捆绑文件。
    • 对于我不编辑的 Plist 是否可以将它们与主包一起保留?
    • 是的,plist 是只读的,您无法在应用程序包中更新,但如果不编辑,您可以保留它
    • 我一直在查看代码,我很困惑到底是哪一段代码实际上将 plist 保存到了文档目录中?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 2011-12-02
    相关资源
    最近更新 更多