MQ.
MQ.

Reputation: 375

How to check if (id) object is null in ios?

I have made a function to consume webservices , now I want to check if (id) object is null or not. What I am doing is here:

-(void)callService:(NSString*)request param:(NSString*) parameters completion:(void (^)(NSArray *list, NSError *error))completionHandler
{
    [self.manager POST:request parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {

        NSLog(@"Response Object: %@", responseObject);

        if (![responseObject isKindOfClass:[NSNull class]]) {

            [self methodUsingJsonFromSuccessBlock:responseObject];

            if (completionHandler) {
                //NSLog(@"%@", list);
                completionHandler(list,nil);
            }
        }
        else {
            NSLog(@"Nothing found");
        }
    }failure:^(NSURLSessionDataTask *task, NSError *error) {

        //NSLog(@"Error: %@", [error description]);
        if (completionHandler) {
            completionHandler(nil,error);
        }
    }];
}

but what I have found on break points is when (id) is null it has NSZeroData but no NSNull so it always passes my condition. I am using AFNetworking

Heres the details of response object:

Thanks in advance for helping me out.

Upvotes: 2

Views: 5231

Answers (3)

Pradumna Patil
Pradumna Patil

Reputation: 2220

Try this

Put this on top

#define isNSNull(value) [value isKindOfClass:[NSNull class]]

And then while comparing

if (isNSNull(object) ...

Upvotes: -3

Dimmy3
Dimmy3

Reputation: 1116

This is not the fastest response, but it can be of some use to someone.

Here is what I've been using and what you can do:

In some class, say "defaults.h" you can define following:

#define Secure(x) x != (id)[NSNull null] ? x : @""
#define isSecure(x) x != (id) [NSNull null] ? YES : NO

Later, in your method you can use it like this:

if(isSecure(responseObject)){
    doSuccess
}
else {
    doError
}

First method can be used for example for strings, while the other is general.

Upvotes: 0

John Estropia
John Estropia

Reputation: 17500

Your responseObject is not NSNull, but an NSData (which _NSZeroData is a subclass of).

So what you really want is this condition:

if ([responseObject isKindOfClass:[NSData class]] && ((NSData *)responseObject).length > 0) {
    // ...
}

Upvotes: 5

Related Questions