2016-11-15 106 views
-3

我有一個按鈕,其標題我是從從服務器獲得的響應選擇終止應用程序由於未捕獲的異常「NSInvalidArgumentException」,原因:「 - [__ NSCFString objectForKey:]:

獲得的響應如下所示:

[ 
{"Id":"2","Name":"Alex"}, 
{"Id":"5","Name":"AMark"}, 
{"Id":"1","Name":"Karta"}, 
{"Id":"7","Name":"Juan"}, 
{"Id":"6","Name":"Honky"}, 
{"Id":"3","Name":"Nirauk"}, 
{"Id":"4","Name":"Chinua"} 
] 

和代碼來設置按鈕我下面的標題低於:

_ButtonArray =[[NSArray alloc]initWithObjects:self.b1,self.b2,self.b3,self.b4,self.b5,self.b6, nil]; 

-(void)getList:(NSData *)response 
{ 
    NSArray* Array = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:nil]; 

    NSLog(@"%@", Array); 
    for (UIButton *button in _ButtonArray) { 
     NSLog(@"the tag of button is %ld",(long)button.tag); 
     for (NSDictionary* dict in Array) 
     { 
      if ([[dict objectForKey:@"Id"] intValue] == button.tag) 
      { 
       [button setTitle:[dict objectForKey:@"Name"] forState:UIControlStateNormal]; 
       NSLog(@"the Id is %@",[dict objectForKey:@"Id"]); 
      } 
     } 
    } 
} 

但它崩潰,給這個異常:

「終止應用程序由於未捕獲的異常 'NSInvalidArgumentException',原因是:「 - [__ NSCFString objectForKey:]:無法識別的選擇發送到實例0x7b24a7f0"

我不明白我要去哪裏錯了。請提出錯誤。

的NSLog的結果:

(
     { 
     Id = 2; 
     Name = Alex; 
    }, 
     { 
     Id = 5; 
     Name = AMark; 
    }, 
     { 
     Id = 1; 
     Name = Karta; 
    }, 
     { 
     Id = 7; 
     Name = Juan; 
    }, 
     { 
     Id = 6; 
     Name = Honky; 
    }, 
     { 
     Id = 3; 
     Name = "Nirauk"; 
    }, 
     { 
     Id = 4; 
     Name = "Chinua"; 
    } 
) 
+1

哪條線確切導致崩潰?您是否使用過調試器並通過此代碼?你有沒有在每一行驗證每個變量的值? – rmaddy

+0

是的,當它去的時候if([[dict objectForKey:@「Id」] intValue] == button.tag) { [button setTitle:[dict objectForKey:@「Name」] forState:UIControlStateNormal]; NSLog(@「the Id is%@」,[dict objectForKey:@「Id」]); } – FreshStar

+1

再一次,究竟哪條線會導致崩潰?指出崩潰的那一行。 – rmaddy

回答

1

你能再次確認您的響應格式。是否有上面提到的字典數組,或者它可能有Dict => Array => Dict例如
{ [ {...} ] }

編輯:

我已經執行代碼:
功能工作正常,我覺得問題出在響應字符串轉換爲NSData的

NSString *responseString = @"[{"Id":"5","Name":"AMark"}, {"Id":"1","Name":"Karta"}]"; //你的應答串
方式

NSData *data = [responseString dataUsingEncoding:NSUTF8StringEncoding];

[self getList:data]; //你的函數調用

這段代碼沒有崩潰。

+0

答覆與我上面提到的問題相同。 – FreshStar

+0

@Lovely你可以把'NSNumber * num = [dict objectForKey:@「Id」];'檢查是否在這行崩潰? – PiyushRathi

+0

@Lovely對不起,以上代碼..這是字符串嘗試這個'NSString * numString = [dict objectForKey:@「Id」]; – PiyushRathi

相關問題