我是iOS初学者,我在编码方面遇到了一些麻烦。 通过发送ASIHTTPRequest:
NSURL *url = [NSURL URLWithString:@"http://search.twitter.com/search.json?geocode=37.781157,-122.398720,25km"];
我收到这样的数据:
{
"created_at" = "Fri, 25 Jan 2013 17:48:29 +0000";
"from_user" = "ZacHWallS_SBI";
"from_user_id" = 252712138;
"from_user_id_str" = 252712138;
"from_user_name" = "ZACH WALLS";
geo = "<null>";
id = 294864332490162176;
"id_str" = 294864332490162176;
"in_reply_to_status_id" = 294861687004225537;
"in_reply_to_status_id_str" = 294861687004225537;
"iso_language_code" = en;
location = "BAY AREA CALIFORNIA";
metadata = {
"result_type" = recent;
};
"profile_image_url" = "http://a0.twimg.com/profile_images/3029389178/e3567459d147bc5d0a10f3c797b477aa_normal.png";
"profile_image_url_https" = "https://si0.twimg.com/profile_images/3029389178/e3567459d147bc5d0a10f3c797b477aa_normal.png";
source = "<a href="http://twitter.com/#!/download/ipad">Twitter for iPad</a>";
text = "@LilTioSBi yee ima slide through prolly";
"to_user" = LilTioSBi;
"to_user_id" = 35629694;
"to_user_id_str" = 35629694;
"to_user_name" = "Nevin Tio";
},
接下来我这样做:
-(void) requestFinished: (ASIHTTPRequest *) request {
NSString *theJSON = [request responseString];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableArray *jsonDictionary = [parser objectWithString:theJSON];
//NSLog(@"\n\n%@", jsonDictionary);
NSMutableArray *userName = [userinfo objectForKey:@"from_user"];
NSLog(@"\n\n\n%@",userName);
我需要捕获“from_user”。 然后运行,编译器说:[__ NSArrayM objectForKey:]:无法识别的选择器发送到实例0x755bbc0 ... 怎么做得对?
答案 0 :(得分:2)
所以,我将首先澄清一些事情,即它实际上是运行时给你“[__NSArrayM objectForKey:]:无法识别的选择器发送到实例0x755bbc0”错误。
让我们分解一下:
__NSArrayM
听起来像NSArray
一样可疑(NSArray
在技术上称为类群集,这意味着你不会总是在实践中看到NSArray
,只是有效的东西像一个)。
-objectForKey:
是NSDictionary
所以,我们在数组上调用一个我们认为是字典的方法(调用方法=发送消息,或者用ObjC说法中的“选择器”)。
您似乎省略了一些代码,但是如果您只是通过以下内容传递了值:
[jsonDictionary objectForKey:@"results"]
你最终会得到一系列推文。然后,您需要从该数组中获取一个项目以获取其from_user
键。
NSArray *tweets = [jsonDictionary objectForKey:@"results"];
NSDictionary *tweet = [tweets objectAtIndex:0];
NSString *username = [tweet objectForKey:@"from_user"];
答案 1 :(得分:0)
您需要使用:
NSString *userName = [jsonDictionary objectForKey:@"from_user"];
答案 2 :(得分:0)
最有可能的是,你有一系列的推文。所以:
- (void) requestFinished: (ASIHTTPRequest *) request {
NSString *theJSON = [request responseString];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSArray *parsedJson = [parser objectWithString:theJSON];
NSMutableArray *allFromUsers = [NSMutableArray new];
for (NSDictionary *tweet in parsedJson) {
NSString *fromUser = [tweet objectForKey:@"from_user"];
[allFromUsers addObject:fromUser];
}
NSLog(@"allFromUsers = %@", allFromUsers);
// ... etc ...
}
或者只是从parsedJson
数组中获取您想要的个人推文。
答案 3 :(得分:-1)
应该是:
NSMutableArray *userName = [NSMutableArray arrayWithObject:[jsonDictionary objectForKey:@"from_user"]];
或许您只想将名称放在NSString中?
NSString *userName = [jsonDictionary objectForKey:@"from_user"];