0

In my app the user can view his own statistics. I retrieve an array from Parse like this:

...
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    userArray = [objects valueForKey:@"myArray"];
}]; 

The code works just fine when the array actually contains something... But if nothing is saved to the array in Parse.com I get errors..

Example: I run this code to test:

NSLog(@"%lu", (unsigned long)[[userArray objectAtIndex:0] count]);

When the array contains something it logs the correct number (works). But when the array is empty I get this error:

"-[NSNull count]: unrecognized selector sent to instance 0x199084fe0"

I can't figure out what is going on.. Anyone has an idea what is happening?

0

2 Answers 2

1

You're not getting an empty array, you are getting an NSNull. You can read more about the difference here.

Testing for NSNull is trivial. Consider replacing values that aren't NSArrays with nil.

id myArray = userArray.firstObject;
myArray = [myArray isKindOfClass:[NSArray class]] ? myArray : nil;
NSLog(@"%i", [myArray count]); //will log 0 because myArray is nil
Sign up to request clarification or add additional context in comments.

4 Comments

So what exactly is this doing? And how can it help me? I still get the same error..
Why wouldn't you just test if it is null? Like this: id object = myArray[0];// similar to [myArray objectAtIndex:0] if(![object isEqual:[NSNull null]]) { //do something if object is not equals to [NSNull null] }
I guess you could do that too if you prefer having conditional blocks in your code...
Could you take a look at my own answer to the question?
0

I found this code to help on my problem:

id object = userArray[0];

if([object isEqual:[NSNull null]]) {
    NSLog(@"Array is empty");
}

Is this safe to use?

2 Comments

I'm obviously not as advanced as you, but I think I'll go for my solution for now.. But thanks anyway!
Also, this won't catch cases when you get something that isn't an NSNull. Like an NSDictionary or something else you aren't expecting. That's why I used isKindOfClass: to check if it's an NSArray.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.