异常__NSarrayM objectforkey无法识别的选择器发送到实例

时间:2013-09-24 07:52:29

标签: iphone objective-c json ios5

我正在尝试创建登录页面,以phpJson文件获取数据。它工作正常,直到我使用这句话[jsonData objectForKey:@"state"],出现异常。 我试图让另一个dictonary像之前的一些问题的答案。但没有什么与我合作。

输出:

Response code : 200
Resonse ==> [{"state":"true"}]
JasonData  ({state = true})

然后是例外

-[__NSarrayM objectforkey:]: unrecognized selector sent to instance

我是objctive-C的新手 如果你能帮助我 我会很高兴

- (IBAction)loginClicked:(id)sender 
{

    @try 
{



    if([[txtUserName text] isEqualToString:@""] || [[txtPassword text] isEqualToString:@""] ) {
        [self alertStatus:@"Please enter both Username and Password" :@"Login Failed!"];
    } else {
        NSString *post =[[NSString alloc] initWithFormat:@"username=%@&password=%@",[txtUserName text],[txtPassword text]];
        NSLog(@"PostData: %@",post);

        NSURL *url = [NSURL URLWithString:@"http://localhost/services/pages/login.php"]; 


        NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

        NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:url];
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postData];
        NSError *error = [[NSError alloc] init];
        NSHTTPURLResponse *response = nil;
        NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

        NSLog(@"Response code: %d", [response statusCode]);
        if ([response statusCode] >=200 && [response statusCode] <300)
        {
            NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
            NSLog(@"Response ==> %@", responseData);                    

            SBJsonParser *jsonParser = [SBJsonParser new];
            NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
            NSLog(@"%@",jsonData);

            NSLog(@"%@",[jsonData objectForKey:@"state"]);
            NSString *state = [(NSString*) [jsonData objectForKey:@"state"] lowercaseString ];
            NSLog(@"%@", state);
            if([state isEqualToString:@"true"])
            {
                NSLog(@"Login SUCCESS");
                [self alertStatus:@"Logged in Successfully." :@"Login Success!"];

            }
            else 
            {

                NSString *error_msg = (NSString *) [jsonData objectForKey:@"error_message"];
                [self alertStatus:error_msg :@"Login Failed!"];
            }


        } 
        else 
        {
            if (error) NSLog(@"Error: %@", error);
            [self alertStatus:@"Connection Failed" :@"Login Failed!"];
        }
    }
}
@catch (NSException * e) 
{
    NSLog(@"Exception: %@", e);
    [self alertStatus:@"Login Failed." :@"Login Failed!"];
}

1 个答案:

答案 0 :(得分:3)

webserive返回的JSON数据似乎是NSArray而不是NSDictionary。你可以在这里查看,

id jsonData = [jsonParser objectWithString:responseData error:nil];

if([jsonData isKindOfClass:[NSDictionary class]]) {
    NSLog(@"Dictionary");
}
else if([jsonData isKindOfClass:[NSArray class]]) {
    NSLog(@"Array");
}

您的代码崩溃是因为您假设已解析的响应为NSDictionary并传递objectForKey:方法。作为NSArray,它无法识别此方法并引发异常。

现在,如果它是一个NSArray,里面有一个字典,你可以按如下方式阅读,

[[jsonData objectAtIndex:0] objectForKey:@"state"];

希望有所帮助!