Valentin Shamardin
Valentin Shamardin

Reputation: 3658

How to store array of integer between app launches?

I want to store some data as a matrix of integers. For simplicity let's say I want to store this data in an array of integers. After each app launch I want to fill my model using this array. So the question is How to store arrays of integer in sandbox? I don't want to write and rewrite data, maybe only once at first start.

What I tried: I know about storing in plists and storing using NSCoding. But this strategies are used for more complicated models, not just arrays of integers.

EDIT: is it faster to use c-arrays, storing them in txt-files and making own parser?

Upvotes: 3

Views: 125

Answers (3)

Irshad Mansuri
Irshad Mansuri

Reputation: 407

+(void)storeArrayInDeviceWithKey:(NSArray *)arrData withKey:(NSString *)key{

     NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];

     [currentDefaults setObject:[NSKeyedArchiver archivedDataWithRootObject:arrData] forKey:key];

     [currentDefaults synchronize];
}
  • For NSArray you need to little conversation with

    NSKeyedArchiver archivedDataWithRootObject:UR OBJECT
    

Upvotes: 0

DCMaxxx
DCMaxxx

Reputation: 2574

You can either store it in a plist, as you said, it's not a bad idea, it would work and do the job. It's not complicated at all, really, and not only used for complex models.

Else, you might want to use NSUserDefaults :

if (![NSUserDefaults standardUserDefaults] objectForKey:@"AKey"]) {
    [[NSUserDefaults standardUserDefaults] setObject:yourArray forKey:@"AKey"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

Don't forget that you need to wrap your integers into NSNumber. A good practice for that would be using Objective-C's "new" notation : NSNumber * nb = @(42). That is much more readable that [NSNumber numberWithInt:42].

Good luck !

EDIT : According to your edit, no, don't use your own parser, at least for now. Don't try to optimize code when you don't really need it. Especially it it involves "breaking" Objective-C standards (and by that I mean using your own made stuff that might bug, and/or introduce strange behavior where Objective-C provides it's own way to do it). See this answer to know more about too much optimization.

Upvotes: 2

Mundi
Mundi

Reputation: 80265

Plists and NSCoding are used for the simple integers as well.

However, you could just use the NSUserDefaults - that is the simples way:

[[NSUserDefaults standardUserDefaults] setObject:myArray forKey:@"AppData"];

Makes it easy to retrieve later from anywhere as well.

Upvotes: 3

Related Questions