ios - JSON数据解析异常 "objectForKey unrecognized selector"

标签 ios objective-c protocols

您好,我是 ios 的新手,在我的项目中,我在我的应用程序中使用 Web 服务。

在这里,对于服务,我维护单独的背景类并使用“协议(protocol)”获取响应。好没关系。我从服务那里得到了很好的回应。

但我的问题是有时会显示异常,如“objectForKey unrecognized selector send”,有时它加载正常,为什么会出现此问题,请参阅下面的代码。

如果没有数据,它会像警报一样显示没有可用数据,我已经维护了 if 和 else 条件,但为什么会出现这个问题?

后台服务类:-

#import "BacGroundGetMethodServiceClass.h"

@interface BacGroundGetMethodServiceClass ()

@end

@implementation BacGroundGetMethodServiceClass
@synthesize delegate;

- (void)viewDidLoad {
    [super viewDidLoad];
}

-(void)getServieCalling :(NSString*)mainurl{


    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:mainurl]

                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy

                                                       timeoutInterval:60.0];

    [request setHTTPMethod:@"GET"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        if (error != nil) {

            NSLog(@"fundamental network error = %@", error);

            return;
        }

        if ([response isKindOfClass:[NSHTTPURLResponse class]]) {

            NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
            if (statusCode != 200) {

                NSLog(@"Warning; server should respond with 200 status code, but returned %ld", (long)statusCode);
            }
        }

        NSError *parseError;
        NSMutableArray *responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];

        if (responseObject) {


             [self MainService:responseObject];

        }

        else {

            NSLog(@"Error parsing JSON: %@", parseError);

            NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"responseString = %@", responseString);
        }
    }];

    [task resume];
}

-(void)MainService :(NSMutableArray*) mainArrayList{

    [delegate GetCallService : mainArrayList];
}

@end

我的主类:-

@interface Mainclass ()
{
 BacGroundGetMethodServiceClass * Get;
}


- (void)viewDidLoad {
    [super viewDidLoad];

   [Get getServieCalling:@"my url here"];

}
- (void) GetCallService: (NSMutableArray*)mainArrayList{

    dispatch_async(dispatch_get_main_queue(), ^{

    NameArray = [[NSMutableArray alloc]init];
    IdArray = [[NSMutableArray alloc]init];

    if (mainArrayList.count<1) {

            NSLog(@"No data available");

      }else{

      for (NSDictionary * obj in mainArrayList) {

        NSString * Name = [obj objectForKey:@"Name"];
        NSString * Id = [obj objectForKey:@"id"];
        [NameArray addObject:Name];
        [IdArray addObject:Id];
      }

     NSLog(@"final NameArray is %@",NameArray);
     NSLog(@"final IdArray is %@",IdArray);

       });
 }

最佳答案

也许你必须改变这一行

NSMutableArray *responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];

在这

id responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];

然后让 Controller 转换为某种 Objective-C 类型,因为它应该知道它期望从服务调用中得到什么(服务对象是一个抽象,所以它不知道它正在处理什么)。 无论如何,您正在处理可能因网络问题或服务器端而失败的网络操作。 Controller 也必须知道它何时失败。

在这种情况下,也尝试使用 blocks 而不是 protocols ...我发现它可能更可重用,它会阻止你总是写很多代码允许委托(delegate)模式。 看这里:https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithBlocks/WorkingwithBlocks.html或者查看GitHub上的AFNetworking代码,它完全是用 block 做的,你可以看到如何使用它们

添加

对我来说,这完全取决于 OOP。因为我正在构建一个只处理网络连接而不知道它在做什么的抽象对象,所以没有理由保留对发件人(委托(delegate))的引用。它应该只处理服务,然后调用内部端点( block )。 您可以在 block 中使用对 selfweak 引用来避免保留循环。

关于ios - JSON数据解析异常 "objectForKey unrecognized selector",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34588038/

相关文章:

ios - 完整 UIScrollView 的快照

ios - 获取午夜后的当前日期,Objective C

ios - 快速进行 iOS 单元测试

ios - 如何将 Obj-C block 保存在 C 结构中?

ios - Swift 中单例类的委托(delegate)

objective-c - 关于 Objective-C 中的协议(protocol)

iphone - 多点裁剪后的UIImage如何保存?

ios - 如何停止信标监控

ios - 您如何处理具有非 Apple 帐户系统的应用程序中的自动续订订阅?

swift - 'Box' 要求 'CanFly' 是类类型