2011-08-08 46 views
1

我使用plist在我的應用程序中,我可以將值添加到plist及其工作正常。但我需要的只是3值應該被加入到plist,此後如果嘗試添加更多的值應該覆蓋前面的三個值上EON後續添加..one由..將3個值添加到plist動態,然後一個接一個覆蓋一個,如果添加更多

這裏是我的代碼,增加了許多x值:

-(void) myplist :(id) sender 
{ 

NSLog(@"mylist Clicked");  
    NSMutableArray *array = [[NSMutableArray alloc] init]; 

// get paths from root direcory 

NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 

// get documents path 

NSString *documentsPath = [paths objectAtIndex:0]; 

NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0]; // get the path to our Data/plist file 
NSLog(docsDir); 

NSString *plistPath = [docsDir stringByAppendingPathComponent:@"Data.plist"]; 

//This copies objects of plist to array if there is one 
[array addObjectsFromArray:[NSArray arrayWithContentsOfFile:plistPath]]; 
[array addObject:searchLabel.text]; 
// This writes the array to a plist file. If this file does not already exist, it creates a new one. 

[array writeToFile:plistPath atomically: TRUE]; 

}

回答

2

您將需要保存一個變量來存儲最後一項插入的索引(lastInsertionIndex below)。假設plist中目前有&第四屆一個被插入3項(lastInsertionIndex = 2),代碼看起來應該是喜歡 -

// get paths from root direcory 

NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 

// get documents path 

NSString *documentsPath = [paths objectAtIndex:0]; 

NSString *docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0]; // get the path to our Data/plist file 
NSLog(docsDir); 

    NSString *plistPath = [docsDir stringByAppendingPathComponent:@"Data.plist"]; 

    //This copies objects of plist to array if there is one 
    [array addObjectsFromArray:[NSArray arrayWithContentsOfFile:plistPath]]; 

//If plist has less than 3 items, insert the new item. Don't use lastInsertionIndex. Else, replace one of the items. 
if([array count] < 3) 
{ 
    [array addObject:[searchLabel.text]]; 
} 
else 
{ 
//Update lastInsertionIndex 
lastInsertionIndex++; 
lastInsertionIndex %= 3; // Max size of array = 3 

[array replaceObjectAtIndex:lastInsertionIndex withObject:[searchLabel.text]]; 
} 

[array writeToFile:plistPath atomically: TRUE]; 

HTH,

阿克沙伊

+0

喜阿克沙伊感謝您的回覆...你能告訴我lastInsertionIndex是怎麼聲明的.. – Ranjit

+0

如果你需要在你的應用程序的生命週期中寫入你的plist,你還需要保存lastInsertionIndex。你可以使用NSUserDefaults來保存它。如果它解決了您的問題,請將其標記爲答案。 – Akshay

+0

好吧,其實當我使用你的代碼時,編譯器給出了一個錯誤,說「未聲明的標識符lastinsertionindex。」..所以該怎麼辦.. – Ranjit

相關問題