After a NSArray was alloc and init, if there is nothing added to the NSArray, how to check it is null or empty ?
Thanks.
if (array == nil || [array count] == 0) {
...
}
nil
when dealing with objects (see stackoverflow.com/questions/557582/null-vs-nil-in-objective-c).nil
object is ignored in Objective-C and will yield 0
. Therefore if ([array count] == 0) { ... }
is enough.nil
is effectively ignored then. OK? It won't crash like pretty much every other language.While we are all throwing out the same answers, I thought I would too.
if ([array count] < 1) {
...
}
nil
-- it's well defined.and another
if(!array || array.count==0)
Try this one
if(array == [NSNull null] || [array count] == 0) {
}
[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).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.You can use this :
if (!anArray || [anArray count] == 0) {
/* Your code goes here */
}
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];
}