2011-09-25 14 views
0

以下代码不能按预期工作。我在创建视图之后但在显示之前设置了一个数组。我使用NSLog来测试数组是否已设置,但if/else将数组视为空。objective-c无nil阵列在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; 
+0

你可以在代码中定义数组吗?最后一段代码被称为“声明”数组。 – chown

回答

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

扩展,这变为:

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

因此,基本上,它看起来像你有你的NSLog()声明在错误的分支。

+0

+这是正确的。该数组不是空的或零,所以其他的得到evald为真,和nslog打印。 – chown

+0

NSLog如何为其他部分工作“Planlist为空”如果planListArr为零且其计数返回0 –

+1

@ Praveen-K如果数组为“nil”或空,那么“”Planlist为空“'不会是记录(在当前代码中)。 –

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");