在使用alloc和init初始化一个NSArray后,如果没有向其中添加任何元素,如何检查该NSArray是否为空?
谢谢。
if (array == nil || [array count] == 0) {
...
}
NSArray有count方法,通常的做法是...
if (![self.myArray count])
{
}
这将检查数组是否为空,或者是否设置为nil。
虽然我们都在提供同样的答案,我也想提供一下我的看法。
if ([array count] < 1) {
...
}
nil
,则objc消息在这种情况下将返回0 -- 这是很好定义的。 - justin还有另外一个
if(!array || array.count==0)
if([myarray count])
它检查数组既不为空也不为nil。
if([arrayName count]==0)
{
//array is empty.
}
else
{
//array contains some elements.
}
试试这个
if(array == [NSNull null] || [array count] == 0) {
}
[NSNull null]
是NSNull
类型的一个对象。因此,如果array == [NSNull null]
,那么array
就是指向该NSNull
单例对象的指针。在想要存储对象(例如在字典或数组中)但不接受nil
时,经常使用[NSNull null]
。如果array == nil
,那么这意味着array
被清零(指向0x0)。 - Robarray == [NSNull null]
不是一个非常有用的检查方式,因为例如如果分配和初始化失败,它将是 nil
而不是 [NSNull null]
。鉴于 user403015 概述的情况,[NSNull null]
不是可能出现的情况。 - Rob使用
(array.count ? array : nil)
array = nil
或者[array count] == 0
,它将返回nil。if (!anArray || [anArray count] == 0) {
/* Your code goes here */
}
if (array == nil && [array count] == 0) {
...
}
我使用这段代码是因为当我的pickerview数组为空时,我遇到了麻烦
我的代码如下:
- (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];
}
nil
(参见 https://dev59.com/YnRB5IYBdhLWcg3wpoxm)。 - user94896nil
对象发送消息会被忽略并返回0
。因此,使用if ([array count] == 0) { ... }
就足够了。 - trojanfoe