2011-03-10 48 views
0

我想,以确定是否一个NSString的值保持高于NULL /零以外的值,而我没有做正确:确定是否NSString的包含一个值以外的NULL/NIL

NSString *strWord; 
strWord = [NSString stringWithFormat: @"%@", [someArray objectAtIndex:x]]; 

// THIS IS WRONG: 

if (strWord != nil) { 
    // do something 
} else { 
    // don't do something 
} 

任何帮助表示赞赏! LQ

+0

为什么这是错的?对于!= nil的检查看起来对我来说完全合理。您可能需要在声明它时设置strWord = nil。 – 2011-03-10 02:20:17

+0

@Stephen:声明时设置strWord = nil根本不会做任何事情,因为该值将立即被'[NSString stringWithFormat:...]'的结果覆盖' – 2011-03-10 02:23:49

+0

您正在通过调用' + stringWithFormat:'。它永远不会返回零。你打算测试什么? – 2011-03-10 02:27:28

回答

2

我怀疑你的问题是strWord实际上包含@"(null)",这是如果你在+stringWithFormat:传递nil%@格式令牌会发生什么。相反,您要检查[someArray objectAtIndex:x]是否为nil。幸运的是,有一条捷径。只要用这个代替:

NSString *strWord = [[someArray objectAtIndex:x] description]; 

这等同于[NSString stringWithFormat:@"%@", [someArray objectAtIndex:x]]除非[someArray objectAtIndex:x]nil然后strWord将包含nil,而不是@"(null)"。原因是%@格式令牌简单地在传递的参数上调用-description,除了特殊情况nil并将其转换为@"(null)"。然而,直接调用-description将直接跳过nil检查,如果在nil上调用,则只需返回nil

+0

是的,它返回@“(null)”,但我无法找出一种方法来检查@“(null)”值,因为这不起作用:if(strWord!= null)...谢谢许多! – 2011-03-10 02:31:57

+0

对不起,使用:NSString * strWord = [[someArray objectAtIndex:x] description];仍然包含(null)并正在通过:if(strWord!= nil)检查。 – 2011-03-10 14:52:42

+0

这意味着''someArray objectAtIndex:x]'本身正在返回'@“(null)”'。要么是这个,要么'strWord'实际上有'@“”',这意味着你有'[NSNull null]'而不是。你应该仔细看看'[someArray objectAtIndex:x]'正在返回。 – 2011-03-10 22:39:17

1

@Kevin Ballard的技术很有用,但请记住[someArray objectAtIndex:x]不能返回零,除非someArray为零(您不能在NSArray中将无)。最接近它可以返回+[NSNull null],这是不一样的事情。所以如果你在这里得到“(null)”,那表明你的数组实际上是零。我可能会在你的方法中早些检查,而不是在字符串中寻找@“(null)”的特殊情况。

相关问题