检查对象实例的属性是否为'空'

检查对象实例的属性是否为'空'

问题描述:

我试图实现下面的代码没有成功。基本上,我想设置为使用thisPhoto.userFullName显示名称,如果它不是“空白”,否则显示thisPhoto.userName代替。检查对象实例的属性是否为'空'

UILabel *thisUserNameLabel = (UILabel *)[cell.contentView viewWithTag:kUserNameValueTag]; 

NSLog(@"user full name %@",thisPhoto.userFullName); 
NSLog(@"user name %@",thisPhoto.userName); 
if (thisPhoto.userFullName && ![thisPhoto.userFullName isEqual:[NSNull null]]) 
{ 
    thisUserNameLabel.text = [NSString stringWithFormat:@"%@",thisPhoto.userFullName]; 
} 
else if (thisPhoto.userFullName == @"") 
{ 
    thisUserNameLabel.text = [NSString stringWithFormat:@"%@",thisPhoto.userName]; 
} 

目前,即使userFullName是空白的,我userName仍没有显示在屏幕上。

+1

请记住,如果您在对象中使用'==',它会比较它们的指针。请参阅下面的关于您应该使用的方法的更多细节。 – 2011-06-02 19:59:27

我在这里看到了几个点

首先 - 如果你userFullName实例变量NSString*然后做简单的比较与nil是不够的:

if (thisPhoto.userFullName) 

当然,除非你明确地将其设置为[NSNull null],然后要求你写的条件。

二 - 比较字符串与isEqualToString:方法,因此第二个条件做了应该改写为:

if ([thisPhoto.userFullName isEqualToString:@""]) { 
    ... 
} 

三 - 有逻辑缺陷 - 如果你的userFullName等于空字符串(@"")的代码仍落入到第一个分支。即空字符串(@"")不等于[NSNull null]或简单零。因此你应该写分支 - 一个处理空字符串和零,另一个处理正常值。所以,带着几分重构你的代码变成这样:

thisUserNameLabel.text = [NSString stringWithFormat:@"%@",thisPhoto.userFullName]; 
if (!thisPhoto.userFullName || [thisPhoto.userFullName isEqualToString:@""]) { 
    // do the empty string dance in case of empty userFullName. 
} 

如果像我想,thisPhoto.userFullNameNSString您可以尝试

[thisPhoto.userFullName isEqualToString:@""] 

我宁愿

if([thisPhoto.userFullName length]) 
+0

我知道“零意味着虚假”和“非零意味着真实”,但这种类型的代码让我尖叫,因为它使意图不明确。当作者以外的人看到他们会说:“作者是否忘记将该值与另一个整数进行比较?”。在这种情况下,省略比较的右侧是恕我直言的丑陋代码。 – octy 2011-06-03 13:07:05

使用-length。只要字符串是nil或空字符串@"",它将为0。你一般都想同时对待这两种情况。

NSString *fullName = [thisPhoto userFullName]; 
thisUserNameLabel.text = [fullName length]? fullName : [thisPhoto userName]; 

// this assumes userFullName and userName are strings and that userName is not nil 
thisUserNameLabel.text = [thisPhoto.userFullName length] > 0 ? thisPhoto.userFullName : thisPhoto.userName; 

其他两个答案是正确的,打我给它。而不是重复他们所说的话 - 我会指出其他的东西。

[NSNull null]用于存储在集合类(NSArrayNSSetNSDictionary)不允许被存储在其中nilnil值。

所以,除非你检查,你从一个集合中获取值 - 没有点检查,对[NSNull null]

“空白”意味着@"",也@" "@"\n"。所以我会修剪userFullName并检查该字符串的长度。

if ([[thisPhoto.userFullName stringByTrimmingCharactersInSet: 
     [NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0) { 

    // it's blank! 
}