简体   繁体   English

在iPhone中将值保存并检索到NSUserDefault中

[英]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. 我正在使用NSUserDefault来保存和检索“保存代码”的值。

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. 我需要从NSUserDefault其他页面保存一个值,并在其他页面上检索并添加数组并显示在表上。

I want to add 10 name to NSUserDefault one by one and retrive from userdefault and display. 我想将10个名称NSUserDefault添加到NSUserDefault ,然后从userdefault中检索并显示。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM