2014-03-04 39 views
1

我使用一个Web API和例如返回:最好的办法NSString的关键值转换为NSDictionary中

access_token=aZDi8ZlmDL34YyxCQt0jXdsRl9Kcinye8r8ilwqCOe3-OII2B96XblSyK7urG4DvPYc&expires_in=1396212623&is_voice_enrolled=false&device_id=3

所以,我需要分裂这个单一字符串键/值对。

的access_token:aZDi8ZlmDL34YyxCQt0jXdsRl9Kcinye8r8ilwqCOe3-OII2B96XblSyK7urG4DvPYc

expires_in:1396212623

is_voice_enrolled:假

DEVICE_ID:3

什么是转换的最佳方式?我应该拆分&,然后再拆分=符号吗?

谢谢!

+1

这实质上是如下面的(具有相同的溶液)同样的问题:http://stackoverflow.com/questions/3997976/parse-nsurl-query-property – rmaddy

回答

4

是的,拆分上&,然后=,这样的:

NSString* data = @"access_token=aZDi8ZlmDL34YyxCQt0jXdsRl9Kcinye8r8ilwqCOe3-OII2B96XblSyK7urG4DvPYc&expires_in=1396212623&is_voice_enrolled=false&device_id=3"; 

NSMutableDictionary* result = [@{} mutableCopy]; 
[[data componentsSeparatedByString:@"&"] enumerateObjectsUsingBlock:^(NSString* obj, NSUInteger idx, BOOL *stop) { 
    NSArray* components = [obj componentsSeparatedByString:@"="]; 
    result[components[0]] = components[1]; 
}]; 

NSLog(@"%@", result); 
+0

很棒:)谢谢你。这似乎比我写的方式更有效率。 – Alan

2

是的,由&,然后由=分开。