views:

2186

answers:

1

I'm making an iPhone app where I want to save state of the Application. This includes an int property which I'm persisting to a file on its own. I have it written and working, but I know the way I did it was a bit hacky, converting the int to a String and then NSData. Can anybody suggest a better way?

int someInt = 1;
NSString *aString = [NSString stringWithFormat:@"%d",someInt];
NSData *someData = [aString dataUsingEncoding:NSUTF8StringEncoding];
[someData writeToFile:[documentsDirectory stringByAppendingString:@"someFile"] atomically:YES];

And then reading it from disk and putting it back into an int -

NSData* someData = [NSData dataWithContentsOfFile:[documentsDirectory stringByAppendingString:@"someFile"]];
NSString *aString = [[NSString alloc] initWithData:someData encoding:NSUTF8StringEncoding];
int someInt = [aString intValue];
+6  A: 

To write:

int i = 1;
NSData *data = [NSData dataWithBytes: &i length: sizeof(i)];
[data writeToFile: [documentsDirectory stringByAppendingString: @"someFile"] atomically: YES]

and to read back:

NSData *data = [NSData dataWithContentsOfFile: [documentsDirectory stringByAppendingString: @"someFile"]];
int i;
[data getBytes: &i length: sizeof(i)];

However, you really should be using NSUserDefaults for something like this, in which case you'd be doing:

[[NSUserDefaults standardUserDefaults] setInteger: i forKey: @"someKey"]

to write, and

int i = [[NSUserDefaults standardUserDefaults] integerForKey: @"someKey"];

to read.

Benjamin Pollack
Isn't NSUserDefaults just for user preferences that are adjusted in the preferences app?
bpapa
No; although you can, it's also safe (and common) to store app behavior information there, even if there is no user interface available. Safari on OS X uses the user defaults to save things such as last window size, whether developer features are enabled, and so on.
Benjamin Pollack