Search code examples
objective-cmacoscore-datansuserdefaults

NSUserDefaults with big array


I'm building a macOS application.

I'm currently using NSUserDefaults to save NSMutableArray data with this method:

-(void)addPhotoUrl:(NSString*)url {
    [self.photosArray addObject:url];

    [[NSUserDefaults standardUserDefaults] setObject:self.photosArray forKey:@"kPhotos"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

And every time the application start I run this code to load the NSMutableArray:

-(void)loadPhotosLike {
    NSArray *myRepository = [[NSUserDefaults standardUserDefaults] arrayForKey:@"kPhotos"];
    if(myRepository && [myRepository count] != 0) {
        [self.photosArray addObjectsFromArray:myRepository];
    }
}

Until now it's work perfectly, But since the array becomes really big(64,000 items), I start to think this solution was not good enough.

There is the issue that the Array exists both in the local NSMutableArray and saved to the NSUserDefaults every time I add a new item to it, this is a good solution and not impact the local memory/app memory/writing problem to the disk?

Should I start using Core Data instead?

One of the main purposes of the array is to search for objects. Will this be faster with CoreData?


Solution

  • As per my exprience NSUserDefaults only use for light weight data like some preferences related data you can store in userDefaults.

    Also if you store heavy/large data it will slower your app as it will store in single plist file.

    And due to heavy data load on app it will create memory issue and as you are working on MacOS you will find memory issue rarely but in term of iOS it will definitely create problem.

    I found very good blog of Jeffrey fulton where he define in detail where we needs to use UserDefaults or where not.

    Link : UserDefaults Limitations and Alternatives

    Also adding to above UserDefault is not safe storage as data can be easily retrievable.

    In your case you can use Core Data or SQLIte both are very powerful and easy to use framework for storing data.

    Hope this will helps.