开发者

how to check nsuserdefaults is empty or not

i am getting a list of items from sqlite database and place them in an array.

i need to get this array first time my app runs.

for this i am saving this array into NSuserdafaults.

my code is like this

if ([[NSUserDefaults standardUserDefaults] arrayForKey:@"categories"]) {

        [[NSUserDefaults standardUserDefaults] setObject:appdelegate.categoriesList forKey:@"categories"];
        NSLog(@"categorylist>>>>>> %@",appdelegate.categoriesList);
    }
    categoriesArray = [[NSM开发者_运维技巧utableArray alloc]init];
    categoriesArray = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"categories"] mutableCopy];

then it not entered into if condition.

and if i try with not equal like this.

if (![[NSUserDefaults standardUserDefaults] arrayForKey:@"categories"]) {

        [[NSUserDefaults standardUserDefaults] setObject:appdelegate.categoriesList forKey:@"categories"];
        NSLog(@"categorylist>>>>>> %@",appdelegate.categoriesList);
    }
    categoriesArray = [[NSMutableArray alloc]init];
    categoriesArray = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"categories"] mutableCopy];

then enter for every build and run.

But i need this for first build and run i mean at installing time.

can any one please help me.

Thank u in advance.

(let me add comment if any one did n't understand my question)


categoriesArray = [[NSMutableArray alloc]init];
categoriesArray = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"categories"] mutableCopy];

The lines above create a leak: you first allocate one array, and then you immediately assign a different array to the same pointer that was keeping track of the array that you allocated. After the second line, you have no way to release the first array.

As for the main question, I suspect that the check

if (![[NSUserDefaults standardUserDefaults] arrayForKey:@"categories"]) {

succeeds every time because there's never a value written for the key @"categories". I see that the lines inside that conditional block try to write a value, but appdelegate.categoriesList may well be nil.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜