objective-c iPhone-int 到 NSData?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/836681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iPhone - int to NSData?
提问by bpapa
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?
我正在制作一个 iPhone 应用程序,我想在其中保存应用程序的状态。这包括一个 int 属性,我将它自己持久化到一个文件中。我已经编写并运行了它,但我知道我这样做的方式有点笨拙,将 int 转换为 String 然后转换为 NSData。有人可以提出更好的方法吗?
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 -
然后从磁盘读取它并将其放回 int -
NSData* someData = [NSData dataWithContentsOfFile:[documentsDirectory stringByAppendingString:@"someFile"]];
NSString *aString = [[NSString alloc] initWithData:someData encoding:NSUTF8StringEncoding];
int someInt = [aString intValue];
回答by Benjamin Pollack
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 NSUserDefaultsfor something like this, in which case you'd be doing:
但是,你真的应该使用这样NSUserDefaults的东西,在这种情况下你会做:
[[NSUserDefaults standardUserDefaults] setInteger: i forKey: @"someKey"]
to write, and
写,和
int i = [[NSUserDefaults standardUserDefaults] integerForKey: @"someKey"];
to read.
阅读。

