3

我正在使用下面的代码将一个新数组添加到 plist 中,但是每次我在我的应用程序中添加一个带有文本字段的新数组时,它都会覆盖旧数组,即使它有一个全新的键..有什么想法吗?

- (IBAction)saveViewerItems
{
    // get paths from root direcory
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    // get documents path
    NSString *documentsPath = [paths objectAtIndex:0];
    // get the path to our Data/plist file
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"];

    // set the variables to the values in the text fields
    self.data = [[NSMutableArray alloc] initWithCapacity:20];


    // create dictionary with values in UITextFields
    NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: data, nil] forKeys:[NSArray arrayWithObjects: (@"%@", text), nil]];

    NSString *error = nil;
    // create NSData from dictionary
    NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDict format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];

    // check is plistData exists
    if(plistData)
    {
        // write plistData to our Data.plist file
        [plistData writeToFile:plistPath atomically:YES];
    }
}
4

2 回答 2

3

为了获取文件中已有的词典,请使用:

NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:(NSString *)filePath];

为了在该字典中写入另一个数组(使用不同的键),请使用:

[dictionary setObject:(id)myArray forKey:(NSString *)myKey];

为了写回文件,请使用:

[dictionary writeToFile:(NSString *)filePath atomically:YES];

没有必要使用NSData类。有关更多信息,请查看Apple NSDictionary 类

于 2013-02-13T15:19:24.547 回答
1

试试这个

    // get paths from root direcory
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    // get documents path
    NSString *documentsPath = [paths objectAtIndex:0];
    // get the path to our Data/plist file
    NSString *plistPath = [documentsPath stringByAppendingPathComponent:@"Data.plist"];

    NSMutableDictionary *plist = [[NSDictionary dictionaryWithContentsOfFile:plistPath] mutableCopy];

    // set the variables to the values in the text fields
    self.data = [[NSMutableArray alloc] initWithCapacity:20];

   [plist setObject:[NSArray arrayWithObjects: data, nil] forKey:forKeys:[NSArray arrayWithObjects: (@"%@", text)];
   [plist writeToFile:path atomically:YES];
   [plist release];
于 2013-02-13T15:20:55.977 回答