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];
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+
An NSData object is simply a container of bytes (raw binary data in the form of 1's and 0's).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With