2012-04-13 51 views
1

串,我发现一个代码片段here,我想用,但我无法弄清楚如何使它回到“串”,看看它是否工程...JSON在iOS5中

// 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]; 

非常感谢!

回答

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 …]; 
+0

这非常非常简单!非常感谢!你是什​​么意思“不要忘记autorelease”?我对iOS开发很陌生,但是这不是因为ARC而弃用了吗? – Michal 2012-04-13 16:21:49

+0

如果您使用ARC,那么是的,您可以(必须!)跳过发布。由于遗留代码和库,并非所有人都使用ARC。 – 2012-04-14 03:32:35

+0

@MarceloCantos你可能想指出究竟是什么需要在这里发布。在这种情况下,它是字符串'repr',因为它是使用alloc-init创建的。根据我的理解,json对象应该是一个自动释放对象。 – pnizzle 2015-03-11 07:24:24