How to check NSArray is null or empty in iOS?
After a NSArray was alloc and init, if there is nothing adde开发者_如何转开发d to the NSArray, how to check it is null or empty ?
Thanks.
if (array == nil || [array count] == 0) {
...
}
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.
While we are all throwing out the same answers, I thought I would too.
if ([array count] < 1) {
...
}
and another
if(!array || array.count==0)
if([myarray count])
It checks for both not empty and nil array.
Try this one
if(array == [NSNull null] || [array count] == 0) {
}
if([arrayName count]==0)
{
//array is empty.
}
else
{
//array contains some elements.
}
You can use this :
if (!anArray || [anArray count] == 0) {
/* Your code goes here */
}
use
(array.count ? array : nil)
It will return nil if array = nil
as well as [array count] == 0
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];
}
精彩评论