开发者

Adding data to the plist dynamically and populating the tableview cells

开发者 https://www.devze.com 2023-03-25 06:10 出处:网络
I am developing an application where i have created the plist, and i am adding data to it..but what is happening is that everytime the data is overwritten and the previous data is lost. I mean suppose

I am developing an application where i have created the plist, and i am adding data to it..but what is happening is that everytime the data is overwritten and the previous data is lost. I mean suppose i add one name called rocky, next time when i add rock, rocky gets overwritten with rock, but what i want is my plist should contain both rocky and rock and so on...I am adding the data in plist by user entry....

here is my code below..

-(IBAction) myplist:(id) sender//the data is saved in a plist by clicking on this button
{
NSLog(@"mylist  Clicked");    

NSMutableArray *array = [[NSMutableArray alloc] init];

[array addObject:searchLabel.text];

   // get paths from root direcory

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

// get documents path

NSString *documentsPath = [paths objectAtIndex:0];

// get the path to our Data开发者_JAVA百科/plist file

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



// 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];
}


I think this will serve your purpose with a slight modification to your code.

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];

// get the path to our Data/plist file

NSString *plistPath = [documentsPath 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];


Try to use a sequence to store data to pList.

1., retrieve old data from pList into a NSMutableDictionary/NSMutableArray

2., add a new record into the NSMutableDictionary/NSMutableArray

3., write to file


You cant append data to Plist. Since you are doing writeToFile each time , the plist file gets re-written. So the data u stored initially will not be there in it. The only other way to achieve wat u desire is to retrieve the array of data from the plist. Then add ur new data object to the array. Write the plist file to disk again with the new appended array. Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消