iPhone - int到NSData?

时间:2009-05-07 19:53:36

标签: iphone objective-c nsdata

我正在创建一个iPhone应用程序,我希望保存应用程序的状态。这包括一个int属性,我将自己持久保存到文件中。我有它编写和工作,但我知道我做的方式是有点hacky,将int转换为String然后转换为NSData。任何人都能提出更好的建议吗?

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

然后从磁盘读取并将其放回int -

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

1 个答案:

答案 0 :(得分:57)

写:

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

并回读:

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

但是,你真的应该使用NSUserDefaults来做这样的事情,在这种情况下你会这样做:

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

写,

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

阅读。