Question

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];
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top