4

This is a classic iOS problem - where should I save my data? I have written a few iOS applications now and have used core data as well as plist files. Furthermore, I normally use NSUserDefaults to save user settings, which is essentially one small dictionary with keys and values. In my (perhaps incorrect) opinion, NSUserDefaults is the simplest way to store information that is required globally in an application.

I have relational data that is being downloaded from a server as a JSON object and was wondering how far I could push NSUserDefaults. My data could be as large as a few megabytes in size. I know NSUserDefaults will handle this as I have tried, however, are there any risks involved with saving the data in this way, despite the fact it isn't necessarily for storing large large amounts of data? Would my app get rejected? Could there potentially be memory and performance issues?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Rambatino
  • 4,716
  • 1
  • 33
  • 56
  • See http://stackoverflow.com/questions/5520797/when-not-to-abuse-nsuserdefaults – Paul Cezanne Nov 02 '13 at 18:18
  • and http://stackoverflow.com/questions/6173625/what-are-the-limitations-of-nsuserdefaults especially the answer which mentions "main thread." – Paul Cezanne Nov 02 '13 at 18:19
  • I can't add more info to the @PaulCezanne answer, but AFAIK your app is not going to be rejected if you go with NSUserDefaults to store large data. – amb Nov 02 '13 at 18:26

1 Answers1

3

You should definitely use other mechanism. NSUserDefaults is ok for small values, but for larger ones you could use the file system. For example:

    NSString* path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    path = [path stringByAppendingPathComponent:@"Private Documents"];
    path = [path stringByAppendingPathComponent:@"YourAppName"];
    [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];

    NSString *filePath = [self.basePath stringByAppendingPathComponent:@"filename.json"];

    // Now save or load the data using NSData or an NSInputStream
    NSInputStream *inputStream = [NSInputStream inputStreamWithFileAtPath:resource];
    [inputStream open];

    id object = [NSJSONSerialization JSONObjectWithStream:inputStream options:0 error:nil];

    // you can write JSON objects in a similar way
gimenete
  • 2,649
  • 1
  • 20
  • 16