objective-c none nil数组在if / else语句中出现为nil

时间:2011-09-25 18:00:03

标签: iphone objective-c if-statement

以下代码未按预期工作。我在创建视图之后但在显示之前设置了一个数组。我使用NSLog来测试数组是否已设置,但if / else将数组视为空。

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    NSLog(@"Planlist is nil %d / has %d objects", (planListArr == nil), [planListArr count]);

    if (planListArr == nil || [planListArr count] == 0) { ... }
    else {
        NSLog(@"Planlist is empty");
    }
}  

日志

2011-09-25 13:54:39.764 myVI[2938:13303] Planlist is nil 0 / has 8 objects
2011-09-25 13:54:39.765 myVI[2938:13303] Planlist is empty

PlanList定义为

NSArray *planListArr;

@property (nonatomic, retain) NSArray *planListArr;

2 个答案:

答案 0 :(得分:4)

if (planListArr == nil || [planListArr count] == 0) { ... }
else {
    NSLog(@"Planlist is empty");
}

扩展,这变为:

if (planListArr == nil || [planListArr count] == 0) {
    ...
} else {
    NSLog(@"Planlist is empty");
}

所以基本上,看起来你的NSLog()语句在错误的分支中。

答案 1 :(得分:2)

(!plainListArray && [plainListArray count]>0) ? NSLog(@"PlainList array has %d items",[plainListArray count] : NSLog(@"Oops! Array is not been initialized or it has no items");