Can NSUserdefaults save two arrays of same name

醉酒当歌 提交于 2019-12-24 18:19:49

问题


Can NSUserdefault save two arrays of same name or it replaces previous array?


回答1:


yes it replace with same variable and xcode not allowed to duplicate the same name of any object in same class so your application not compile until you not remove any one array name from class...

Update:-

In AppDelegate.h file just declare variable...

NSUserDefaults  *userDefaults;
NSMutableArray *yourArray;

after...

In AppDelegate.m Fille in applicationDidFinishLonching: Method

userDefaults = [NSUserDefaults standardUserDefaults];
    NSData *dataRepresentingtblArrayForSearch = [userDefaults objectForKey:@"yourArray"];
    if (dataRepresentingtblArrayForSearch != nil) {
        NSArray *oldSavedArray = [NSKeyedUnarchiverunarchiveObjectWithData:dataRepresentingtblArrayForSearch];
        if (oldSavedArray != nil)
            yourArray = [[NSMutableArray alloc]initWithArray:oldSavedArray];
        else
            yourArray = [[NSMutableArray alloc] init];
    } else {
        yourArray = [[NSMutableArray alloc] init];
    }
    [yourArray retain];

after that when you want to insert,update or delete Data from this userDefaults Use Bellow Code...

For Delete record use bellow        

[appDelegate.yourArray removeObjectAtIndex:IndexValue];// define integer value here on IndexValue

         or     for insert record use bellow..

       

[appDelegate.yourArray addObject:AddValueHere];

or for replace whole array with new array then write this

appDelegate.yourArray = YourNewArray; 

[appDelegate.yourArray retain];

after that for save whole your data synchronize NSUserDefaults like bellow...         

NSData *data=[NSKeyedArchiverarchivedDataWithRootObject:appDelegate.yourArray];
    [appDelegate.userDefaults setObject:data forKey:@"yourArray"];
    [appDelegate.userDefaults synchronize];


来源:https://stackoverflow.com/questions/13177154/can-nsuserdefaults-save-two-arrays-of-same-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!