58

After a NSArray was alloc and init, if there is nothing added to the NSArray, how to check it is null or empty ?

Thanks.

user403015
  • 7,209
  • 19
  • 66
  • 100

10 Answers10

113
if (array == nil || [array count] == 0) {
    ...
}
  • You should use `nil` when dealing with objects (see http://stackoverflow.com/questions/557582/null-vs-nil-in-objective-c). –  May 09 '11 at 04:41
  • 1
    Should you do both? Or will [array count] == 0 return TRUE if the array is nil? – shim May 07 '14 at 17:50
  • 9
    No you don't need both. Sending a message through a `nil` object is ignored in Objective-C and will yield `0`. Therefore `if ([array count] == 0) { ... }` is enough. – trojanfoe Apr 13 '16 at 10:31
  • @trojanfoe sending a message to nil is NOT ignored, but rather has strict predefined behavior. In this case 'count' message is supposed to return an NSInteger - so it does exactly that. returns zero (0). – Motti Shneor Sep 23 '19 at 16:10
  • @MottiShneor Sending a message to a `nil` is effectively ignored then. OK? It won't crash like pretty much every other language. – trojanfoe Sep 23 '19 at 16:17
  • @trojanfoe not ignored. no. It just has predefined behavior - a message to nil returns the value 0, or NO. – Motti Shneor Oct 31 '19 at 16:31
  • @MottiShneor I said "effectively ignored" and Apple describe sending a message to `nil` as "nothing happening" (see `Working with nil` in this [guide](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithObjects/WorkingwithObjects.html)). Perhaps you should contact the technical authors at Apple and badger them with your lawyer-speak descriptions of this meaningless "pre-defined behaviour". – trojanfoe Nov 01 '19 at 14:16
  • Sorry, but returning a concrete value - isn't really "ignore"... at least not in the 'C' language sense. you could assign that value [nil count]; to a variable, like int 'c = [nil count];' and that would generate real assembly code, to set c to 0 --- by no means your Call to 'count' was ignored. only moved through the 'nil' pseudo object. The difference is important when complicated Obj-C code is written. 'Ignored' means 'not run'. – Motti Shneor Nov 09 '19 at 19:21
24

NSArray has the count method, a common way to do it would be...

if (![self.myArray count])
{
}

That will check if the array has nothing in it, or if it is set to nil.

Joshua Weinberg
  • 28,598
  • 2
  • 97
  • 90
14

While we are all throwing out the same answers, I thought I would too.

if ([array count] < 1) {
    ...
}
itsji10dra
  • 4,603
  • 3
  • 39
  • 59
shabbirv
  • 8,958
  • 4
  • 33
  • 34
  • 1
    +1 for anonymous downvote to a response which is (apart from some people's personal preferences) as good and correct as the others. the reason this works, is because the objc message will return 0 in this case if array is `nil` -- it's well defined. – justin May 09 '11 at 05:00
  • thanks for the upvote. Didn't really understand why i deserved a downvote apart from the witty comment which should be ignored as the only thing that matters is the code. – shabbirv May 09 '11 at 05:07
  • Why < 1 and not == 0? < 1 indicates that we can also get negative numbers and this doesn't seem to be the case. – User May 27 '14 at 19:52
9

and another

if(!array || array.count==0)
Jason Cragun
  • 3,233
  • 1
  • 26
  • 27
  • 2
    that would mean that the array was not nil. but it still could be empty, hence logical or to check to see if the count is 0. If the array is nil (!array), the second part won't even be evaluated. – Jason Cragun Feb 11 '12 at 22:31
  • array.count will be 0 if array is nil. This is well defined Objective-C behavior. Excessive nil checking in Objective-C is something is primarily carried over by Java/C# developers. – Erik Engheim Apr 20 '16 at 11:00
6

if([myarray count]) It checks for both not empty and nil array.

slavoo
  • 5,798
  • 64
  • 37
  • 39
chaithraVeeresh
  • 258
  • 3
  • 11
4
if([arrayName count]==0)
{
    //array is empty.
}
else
{
   //array contains some elements.
}
Soorej Babu
  • 350
  • 2
  • 19
4

Try this one

if(array == [NSNull null] || [array count] == 0) {
}
PgmFreek
  • 6,374
  • 3
  • 36
  • 47
  • What is the difference between (array == [NSNull null]) and (array == nil) ? – user403015 May 09 '11 at 04:55
  • @user403015 `[NSNull null]` is a object of type `NSNull`. Thus if `array == [NSNull null]`, then `array` is a pointer to that `NSNull` singleton object. `[NSNull null` is frequently used when you want to store an object (e.g. in a dictionary or array), where `nil` would not be accepted. If `array == nil` then that means that `array` is zeroed out (points to 0x0). – Rob Aug 10 '12 at 08:09
  • 2
    @OhhMee I don't know who downvoted it, but it's probably because `array == [NSNull null]` is not a very useful check, because, for example, if the alloc and init failed, it would be `nil`, not `[NSNull null]`. Given the scenario that user403015 outlined, `[NSNull null]` is not a scenario that could arise. – Rob Aug 10 '12 at 08:11
3

You can use this :

if (!anArray || [anArray count] == 0) {
    /* Your code goes here */
}
Joel
  • 7,401
  • 4
  • 52
  • 58
RandomGuy
  • 127
  • 1
  • 6
  • @Joel Please explain the reason for downvoting. – RandomGuy Feb 17 '14 at 06:29
  • while it is legit to ask about why you have been downvoted (I'd do it as well), you should **not jump to conclusions**. I'm pretty sure I did not vote your answer (neither up nor down). The only thing I've done was suggest an edit (which has been approved, I see). – Joel Feb 17 '14 at 15:13
3

use

(array.count ? array : nil)

It will return nil if array = nil as well as [array count] == 0

itsji10dra
  • 4,603
  • 3
  • 39
  • 59
infiniteLoop
  • 2,135
  • 1
  • 25
  • 29
1
if (array == nil && [array count] == 0) {
...
}

I use this code because I am having trouble to my pickerview when its the array is empty

My code is

- (IBAction)btnSelect:(UIBarButtonItem *)sender { // 52
if (self.array != nil && [self.array count] != 0) {
    NSString *select = [self.array objectAtIndex:[self.pickerView selectedRowInComponent:0]];

    if ([self.pickListNumber isEqualToString:@"1"]) {
        self.textFieldCategory.text = select;
        self.textFieldSubCategory.text = @"";
    } else if ([self.pickListNumber isEqualToString:@"2"]) {
        self.textFieldSubCategory.text = select;
    }

    [self matchSubCategory:select];
} else {
    UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Error"
                                                          message:@"You should pick Category first"
                                                         delegate:nil
                                                cancelButtonTitle:@"OK"
                                                otherButtonTitles: nil];
    [myAlertView show];
}

[self hidePickerViewContainer:self.viewCategory];
}
user313879
  • 19
  • 1
  • The code in the first line and the code inside the example code is different. – trojanfoe Apr 13 '16 at 10:29
  • The first block has an inherent bug. If (array == nil) how can it ever have a 'count' ??? this if is meaningless, and will always return false. – Motti Shneor Sep 23 '19 at 16:12