Nav*_*avi 61 objective-c nsarray ios nsnull
I am getting an array with null value. Please check the structure of my array below:
(
"< null>"
)
Run Code Online (Sandbox Code Playgroud)
When I'm trying to access index 0 its crashing because of
-[NSNull isEqualToString:]: unrecognized selector sent to instance 0x389cea70
Run Code Online (Sandbox Code Playgroud)
Currently its crashing because of that array with a crash log:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull isEqualToString:]: unrecognized selector sent to instance 0x389cea70'
*** First throw call stack:
(0x2d9fdf53 0x3820a6af 0x2da018e7 0x2da001d3 0x2d94f598 0x1dee57 0x1dfd31 0x302f598d 0x301a03e3 0x3052aeed 0x3016728b 0x301659d3 0x3019ec41 0x3019e5e7 0x30173a25 0x30172221 0x2d9c918b 0x2d9c865b 0x2d9c6e4f 0x2d931ce7 0x2d931acb 0x3262c283 0x301d3a41 0xabb71 0xabaf8)
libc++abi.dylib: terminating with uncaught exception of type NSException
Run Code Online (Sandbox Code Playgroud)
Cha*_*sha 119
id object = myArray[0];// similar to [myArray objectAtIndex:0]
if(![object isEqual:[NSNull null]])
{
//do something if object is not equals to [NSNull null]
}
Run Code Online (Sandbox Code Playgroud)
Ton*_*que 30
if (myArray != (id)[NSNull null])
Run Code Online (Sandbox Code Playgroud)
要么
if(![myArray isKindOfClass:[NSNull class]])
Run Code Online (Sandbox Code Playgroud)
res*_*ode 13
基于托尼的回答,我做了一个宏.
#define isNSNull(value) [value isKindOfClass:[NSNull class]]
Run Code Online (Sandbox Code Playgroud)
然后使用它
if (isNSNull(dict[@"key"])) ...
Run Code Online (Sandbox Code Playgroud)
Awww,伙计们.这是个简单的.
// if no null values have been returned.
if ([myValue class] == [NSNull class]) {
myValue = nil;
}
Run Code Online (Sandbox Code Playgroud)
我确信有更好的答案,但这个有效.
我发现使用的代码NSNull有以下问题:
所以我创建了以下类别:
@interface NSObject (NSNullUnwrapping)
/**
* Unwraps NSNull to nil, if the object is NSNull, otherwise returns the object.
*/
- (id)zz_valueOrNil;
@end
Run Code Online (Sandbox Code Playgroud)
随着实施:
@implementation NSObject (NSNullUnwrapping)
- (id)zz_valueOrNil
{
return self;
}
@end
@implementation NSNull (NSNullUnwrapping)
- (id)zz_valueOrNil
{
return nil;
}
@end
Run Code Online (Sandbox Code Playgroud)
它的工作原理如下:
Class(即该Class类型的单例实例),则行为未定义.但是,允许在子类中声明的方法覆盖其超类中的类别方法.这允许更简洁的代码:
[site setValue:[resultSet[@"main_contact"] zz_valueOrNil] forKey:@"mainContact"];
Run Code Online (Sandbox Code Playgroud)
..而不是有额外的行来检查NSNull.该zz_前缀看起来有点丑,但那里的安全,以避免命名空间冲突.