在Objective C中检查NSString的NOT <null>值的条件

vir*_*ral 2 iphone if-statement objective-c ios

码:

NSString *tempPhone = [NSString stringWithFormat:@"%@", [personDict objectForKey:kPhoneKey]];
NSLog(@"NSString *tempPhone = %@",tempPhone);
Run Code Online (Sandbox Code Playgroud)

输出:

NSString *tempPhone = <null>
Run Code Online (Sandbox Code Playgroud)

现在我想添加if条件,因为不为null ; 我试过以下:

if (tempEmail != NULL)
if (tempPhone != Nil)
if (tempPhone != nil)
if (![tempPhone compare:@"<null>"])
if (tempPhone != (NSString*)[NSNull null])
Run Code Online (Sandbox Code Playgroud)

我也查了这篇帖子.

他们都没有为我工作.我哪里错了?

Ila*_*ian 8

请尝试以下代码

id phoneNo = [personDict objectForKey:kPhoneKey];

if( phoneNo && ![phoneNo isKindOfClass:[NSNull class]] )
{
    NSString *tempPhone = [NSString stringWithFormat:@"%@", [personDict objectForKey:kPhoneKey]];
    NSLog(@"NSString *tempPhone = %@",tempPhone);
}
else
{
    NSLog(@"NSString *tempPhone is null");
}
Run Code Online (Sandbox Code Playgroud)