jay
jay

Reputation: 41

Saving and retriving value into NSUserDefault in IPhone

Hi Some Body Give Me an Idea.

I am useing NSUserDefault To saving and retriving value for Saving Code is.

dataDict_=[[NSMutableDictionary alloc]init];
    [dataDict_ setObject:[nameText_ text] forKey:@"Name"];
    [dataDict_ setObject:[linkText_ text] forKey:@"Link"];
    NSUserDefaults *userDefault=[NSUserDefaults standardUserDefaults];
    [userDefault setObject:dataDict_ forKey:@"Dict"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    [dataDict_ release];

And For retriving Code is

NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *favourites = [[standardUserDefaults objectForKey:@"Dict"]   mutableCopy];

Now the issue is with the help of this code i am able to save and retrive data for one time If i save once again at that time my new value is overlaping to last value.

I need to save a value from other page in NSUserDefault and retrive on other page and add in array and display on table.

I want to add 10 name to NSUserDefault one by one and retrive from userdefault and display.

But With the help of this code only new data i can retrive that meand last data get overlaps to new data.

Please give me the solution how to resolve this.

NSLog(@"The dict value is %@",favourites);

Upvotes: 0

Views: 793

Answers (1)

deanWombourne
deanWombourne

Reputation: 38475

Instead of storing one value, store an array :

// Create a data dictionary for this name & link
dataDict_=[[NSMutableDictionary alloc]init];
[dataDict_ setObject:[nameText_ text] forKey:@"Name"];
[dataDict_ setObject:[linkText_ text] forKey:@"Link"];

// Get the current array from user defaults
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
NSMutableArray *favourites = [[userDefault objectForKey:@"favourites"] mutableCopy];
if (nil == favourites) favourites = [[NSMutableArray alloc] init];

// Add the new details to it
[favourites addObject:dataDict];

// Store the array in the user defaults
[userDefault setObject:favourites forKey:@"favourites"];
[userDefault synchronize];

// Release
[favourites release];
[dataDict release];

Now, to get all the details back out of the user defaults, you get an array instead of one set of details

NSArray *favourites = [[NSUserDefaults standardUserDefaults] objectForKey:@"favourites"];

Upvotes: 1

Related Questions