2013-02-13 35 views
3

我使用下面的代码将新阵列添加到plist,但每次我在我的应用程序中添加一个新的阵列与文本字段覆盖旧的,即使它有一个全新的钥匙..任何想法?iOS新阵列中用新键覆盖旧阵列与不同的键

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

这可能完全是一个的n00b问题(我是真正的新iOS开发),但为什么你把这个数据在plist中,而不是使用核心数据还是SQLite? – 2013-02-13 15:08:41

+0

问题是,每次你没有在plist中添加数据。除此之外,你正在更新plist。因此,这覆盖了旧数据 – 2013-02-13 15:08:58

+0

因为我也是新的,我不知道该怎么做 - 它必须保存的数据非常简单...使用sqlite还是coredata更容易? – 2013-02-13 15:09:57

回答

3

为了获得dictionaty已经在文件中,使用:

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

为了写那本词典另一个数组(使用不同的密钥),使用:

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

为了回写文件,请使用:

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

有没有必要使用NSData类。欲了解更多信息,请Apple NSDictionary Class

+0

这工作 - 非常感谢你! – 2013-02-13 15:31:56

+0

它不会做的是添加plist,如果它不存在... – 2013-02-13 15:32:45

+0

你是什么意思,你能解释一下吗? – Luke 2013-02-13 15:37:16

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]; 
+0

首先获得所有的plist元素然后在该plist对象中添加新对象dthen写入 – 2013-02-13 15:23:11

+0

感谢您的帮助。 FYI'发布'不再适用于iOS,因为自动引用计数不允许。 – 2013-02-13 15:56:57

+0

没问题不需要在这里使用发布! – 2013-02-13 16:55:37