Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone - int to NSData?

Tags:

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];
like image 717
bpapa Avatar asked May 07 '09 19:05

bpapa


People also ask

What is NSData in iOS?

A static byte buffer that bridges to Data ; use NSData when you need reference semantics or other Foundation-specific behavior. iOS 2.0+ iPadOS 2.0+ macOS 10.0+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+

What is NSData object?

An NSData object is simply a container of bytes (raw binary data in the form of 1's and 0's).


1 Answers

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.

like image 179
Benjamin Pollack Avatar answered Oct 25 '22 22:10

Benjamin Pollack