Home > front end >  Objective-C data type issue
Objective-C data type issue

Time:10-28

I'm not that strong with Objective-C, so this is probably a simple issue. I cannot understand why the the last line in the error completion block is causing an exception:

- (void)sendInappropriateNewsfeedComment:(NSString *)comment newsfeedEventId:(NSString *)newsfeedEventId completion:(void (^)(NSString *, NSInteger))completion error:(void (^)(NSString *, NSInteger))error {
    PAInappropriateNewsFeedRequest *inappropriateNewsfeedRequest = [[PAInappropriateNewsFeedRequest alloc] initWithComment:comment newsfeedEventId:newsfeedEventId];
    [inappropriateNewsfeedRequest executeWithCompletionBlock:^(id obj) {
        completion(@"SUCCESS", (NSInteger)1);
    } error:^(NSError *e, id obj) {
        NSString * message = [obj objectForKey:@"message"];

        error(message, [obj integerForKey:@"code"]);
    }];
}

I've also attached a screenshot showing that the "obj" object has a key called "code" that is of type "(long)-1".

debug console

What is the proper way to declare the error block and pass the "-1" value back to the call site?

CodePudding user response:

Simply because NSDictionary has no method called integerForKey. That's what "unrecognized selector" means. Selector is basically a method name.

The fact that this can be even compiled is caused by using id for the parameter type. You can call anything on id but it will crash your app if the method does not exist. You should cast obj to a proper type as soon as possible.

NSDictionary *dictionary = (NSDictionary *) obj;
NSString *message = dictionary[@"message"];
NSNumber *code = dictionary[@"code"];

If obj can be a different type, you should make sure to check [obj isKindOfClass:NSDictionary.self] before casting.

  • Related