代码之家  ›  专栏  ›  技术社区  ›  Reed Olsen

如何将新项目附加到plist?

  •  5
  • Reed Olsen  · 技术社区  · 17 年前

    在我的iPhone应用程序中,我有两个plist文件来存储“主题”。一个是包含默认主题的只读文件,另一个包含用户创建的自定义主题。我使用plist文件是因为从plist中读取和创建新的主题对象非常容易。

    我的plist是一个字典对象数组。

    有什么简单的方法可以将新的字典对象附加到plist文件中吗?或者我需要将文件读取到内存中,附加新的dictionary对象,然后将其写回文件系统吗?

    谢谢!

    3 回复  |  直到 16 年前
        1
  •  5
  •   Nicholas Riley    17 年前

    使用cocoa,您需要将文件读取到内存中,附加新的dictionary对象,然后将其写回文件系统。如果您使用一个XML plist,您可以很容易地解析它并增量地写入文件,但它也会大一点,因此它不太可能值得。

    如果重写plist花费的时间太长,则应使用数据库(可能通过核心数据)进行调查。除非文件很大,我怀疑这将是一个问题,即使iPhone的内存容量和闪存写入速度。

        2
  •  3
  •   Community Mohan Dere    9 年前

    (我为那些不想点击类似问题链接的人复制了这个,我在这里回答了: A question on how to Get data from plist & how should it be layout )

    以下是使用nsdictionary从plist读取和写入值的两种方法:

    - (NSMutableDictionary*)dictionaryFromPlist {
        NSString *filePath = @"myPlist.plist";
        NSMutableDictionary* propertyListValues = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
        return [propertyListValues autorelease];
    }
    
    - (BOOL)writeDictionaryToPlist:(NSDictionary*)plistDict{
        NSString *filePath = @"myPlist.plist";
        BOOL result = [plistDict writeToFile:filePath atomically:YES];
        return result;
    }
    

    然后在代码块的某个地方:

    // Read key from plist dictionary
    NSDictionary *dict = [self dictionaryFromPlist];
    NSString *valueToPrint = [dict objectForKey:@"Executable file"];
    NSLog(@"valueToPrint: %@", valueToPrint);
    
    // Write key to plist dictionary
    NSString *key = @"Icon File";
    NSString *value = @"appIcon.png";
    [dict setValue:value forKey:key];
    
    // Write new plist to file using dictionary
    [self writeDictionaryToPlist:dict];
    
        3
  •  3
  •   Vibhor Goyal    16 年前

    这就是我将数据添加到plist的方式:

        NSString *filePath = [self dataFilePath];
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) 
    {
        NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
        [array addObject:countdownLabel.text];
        [array writeToFile:[self dataFilePath] atomically:YES];
        [array release];
    }
    else
    {
        NSArray *array = [NSArray arrayWithObject:countdownLabel.text];
        [array writeToFile:filePath atomically:YES];
    }