我們需要能夠讀取現有plist文件的內容,然後添加到數組/字典中,然後將這些新數據寫入plist文件。狹窄很簡單。我們需要多個根鍵作爲數組,每個鍵都有一些值。結構看起來像這樣,將數據附加到PLIST - iPhone
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];'那是你想要做的嗎? – DarkDust 2012-01-16 18:01:40
本質上是的,但我們在創建可變數組時遇到了麻煩,增加了數據然後寫出來。我想發佈我們目前如何編寫文件,如果這將有助於 – mejim707 2012-01-16 18:08:51
是的,請編輯您的問題,併發布導致麻煩的代碼。 – DarkDust 2012-01-16 18:16:47