2012-04-13 61 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