【发布时间】:2012-01-16 17:58:00
【问题描述】:
我们需要能够读取现有 plist 文件的内容,然后添加到数组/字典中,然后将这些新数据写入 plist 文件。限制很简单。我们想要多个根键作为数组,每个根键都有几个值。结构是这样的,
124818240124810284.JPG Array
item 0 String Some Attribute 1
item 1 String Some Attribute 2
到目前为止,我们可以毫无问题地创建上述内容。但是,一旦我们将另一个数组写入 plist,文件就会被简单地覆盖,并且所有当前内容都会丢失。我们需要做的是阅读上面的内容并添加到其中,这样我们就得到了这样的东西,
124818240124810284.JPG Array
item 0 String Some Attribute 1
item 1 String Some Attribute 2
354273577823597297.JPG Array
item 0 String Some Attribute 1
item 1 String Some Attribute 2
等等。我们不知所措,已经为此苦苦挣扎了一天。请在力所能及的地方提供帮助!提前致谢!!
我们目前正在编写这个文件如下
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"Gallery.plist"];
// set the variables to the values in the text fields
NSMutableArray *myPhotos = [[NSMutableArray alloc] initWithCapacity:2];
[myPhotos addObject:@"NO"];
[myPhotos addObject:@"NO"];
// create dictionary with values in UITextFields
NSDictionary *plistDict = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: myPhotos, nil] forKeys:[NSArray arrayWithObjects: self.photoName, 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];
}else{
NSLog(@"Error in saveData: %@", error);
[error release];
}
以下是我们最终得到的结果
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"Gallery.plist"];
// Get current content.
NSDictionary *oldContent = [NSDictionary dictionaryWithContentsOfFile:plistPath];
// Make a mutable copy.
NSMutableDictionary *newContent = [[oldContent mutableCopy] autorelease];
// Add new stuff.
NSMutableArray *myPhotos = [[NSMutableArray alloc] initWithCapacity:2];
[myPhotos addObject:@"Attribute 1"];
[myPhotos addObject:@"Attribute 2"];
[newContent setObject:myPhotos forKey:self.filePath];
// Now, write the plist:
[newContent writeToFile:plistPath atomically:YES];
【问题讨论】:
-
那么,从本质上讲,您在向数组添加另一个条目时遇到了麻烦?伪代码:
array = [self readPlist]; array = [array arrayByAppendingObject:newEntry]; [self writePlist:array];这是你想做的吗? -
基本上是的,但是我们在创建可变数组时遇到了麻烦,向其中添加数据然后将其写出。如果有帮助,我想发布我们目前如何编写文件
-
是的,请编辑您的问题并发布导致问题的代码。
-
呃,你连原版的plist都没有看……
-
我刚刚发布了我们用来将数据写入 plist 的代码。同样,这非常有效。您可以看到添加了一些对象,然后告诉这些对象与 self.photoName 的键值链接。一切都很好,但是,我们需要阅读当前列表并添加一些上述内容。谢谢!