I m using plist
in my application,i am able to add the values in the plist
and its work开发者_运维百科ing fine.but what i need is only 3 values should be added to the plist
and thereafter if tried to add more values it should overwrite the previous three values ..one by on eon subsequent additions..
Here is my code which adds many x values:
-(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];
}
You will need to keep a variable that stores the index at which the last item was inserted (lastInsertionIndex below)
. Assuming the plist currently has 3 items & the 4th one is being inserted (lastInsertionIndex = 2), the code should look something like-
// 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,
Akshay
精彩评论