我正在努力处理来自我的一个API调用的响应对象。我收到它很好,但如果我尝试对对象执行count或valueForKey操作,我会收到“无法识别的选择器发送到实例”错误。我有一种感觉,我没有正确解码响应对象,任何输入将不胜感激!
API调用的方法:
- (void)callRegisterAccount:(NSString *)email
password:(NSString *)password
confirmPassword:(NSString *)confirmPassword
completionBlock:(void (^)(NSMutableArray *resultsArray))completion{
NSLog(@"REGISTER ACCOUNT CALLED!");
NSString *appendUrl = [NSString stringWithFormat:@"Account/Register"];
NSURL *aUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@""%@", @"xxx", appendUrl]];
NSLog(@"URL: %@",aUrl);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
[request setHTTPMethod:@"POST"];
[request addValue:@"application/json, text/plain, */*" forHTTPHeaderField:@"Accept"];
[request addValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
//build an info object and convert to json
NSDictionary* info = [NSDictionary dictionaryWithObjectsAndKeys:
email,
@"Email",
password,
@"Password",
confirmPassword,
@"ConfirmPassword",
nil];
//convert object to data
NSError *error;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:info
options:NSJSONWritingPrettyPrinted error:&error];
NSString *strData = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"%@",strData);
[request setHTTPBody:[strData dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
// NSLog(@"REGISTER PUSH NOTIFICATIONS RESPONSE: %@", response);
// NSLog(@"REGISTER PUSH NOTIFICATIONS ERROR: %@", error);
// NSLog(@"REGISTER PUSH NOTIFICATIONS DATA: %@", data);
NSData *_data = data;
NSMutableString *_string = [NSMutableString stringWithString:@""];
for (int i = 0; i < _data.length; i++) {
unsigned char _byte;
[_data getBytes:&_byte range:NSMakeRange(i, 1)];
if (_byte >= 32 && _byte < 127) {
[_string appendFormat:@"%c", _byte];
} else {
[_string appendFormat:@"[%d]", _byte];
}
}
NSLog(@"REGISTER ACCOUNT RESPONSE: %@", _string);
if(_string) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
completion((NSMutableArray*)_string);
}
}];
}
答案 0 :(得分:2)
这一行都错了:
completion((NSMutableArray*)_string);
_string
是NSMutableString
的一个实例,在这里您告诉编译器相信它实际上是NSMutableArray
的一个实例。这显然是一个谎言,当你尝试将它用作数组时,你会得到一个例外。
请注意,JSON可以是数组或字典,在您的示例中,它实际上是一个字典,因此您需要检查并确定如何返回数组 - 或更改完成块。您需要在某处显式处理此容器类型变体...
您不需要将时髦的数据用于字符串处理,您只需使用NSJSONSerialization
直接从数据到JSON对象(字典或数组),它就可以了如果JSON存在问题,则返回错误。
NSJSONSerialization
。