2011-08-08 23 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

相关问题