1

我在这里找到了一个代码片段,我想使用它,但我不知道如何让它回到“字符串”并查看它是否有效......

// some strings for test
NSString *cpu = [[NSString alloc] initWithFormat:@"%.0f", [_cpuSlider value]];
NSString *ram = [[NSString alloc] initWithFormat:@"%.0f", [_ramSlider value]];
NSString *hdd = [[NSString alloc] initWithFormat:@"%.0f", [_hddSlider value]];

// put them into dictionary
NSDictionary *test = [NSDictionary dictionaryWithObjectsAndKeys:cpu, @"CPU", ram, @"RAM", hdd, @"HDD", nil];
// start of the code from page above
NSMutableData *myData = [[NSMutableData alloc]init];  
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:myData];  
[archiver encodeObject:test forKey:@"MyKEY"];  
[archiver finishEncoding];  
id testJson = [NSJSONSerialization JSONObjectWithData:myData options:0 error:nil];
// end of code

// HERE I'd like know what to put in to see it as a string..e.g. { "CPU"=value; etc...}
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"MLIA" message:????? delegate:nil cancelButtonTitle:@"Zavřít" otherButtonTitles: nil];
[av show];

非常感谢!

4

1 回答 1

1

NSKeyedArchiver不产生 JSON (AFAIK),所以我不知道那个链接的例子是如何工作的。如果要对字典进行 JSON 编码,可以使用+dataWithJSONObject:options:error:

NSError *err;
NSData *json = [NSJSONSerialization dataWithJSONObject:test options:0 error:&err];
NSAssert1(json, @"Error: %@", err);

// If not using ARC, remember to (auto)release repr.
NSString *repr = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];

[[UIAlertView …] … message:repr …];
于 2012-04-13T16:10:06.143 回答