NSArray의 객체가 NSNull인지 어떻게 확인할 수 있습니까?
null 값이있는 배열을 얻고 있습니다. 아래에서 내 배열의 구조를 확인하십시오.
(
"< null>"
)
인덱스 0에 액세스하려고 할 때
-[NSNull isEqualToString:]: unrecognized selector sent to instance 0x389cea70
현재 충돌 로그가있는 배열로 인해 충돌이 발생합니다.
*** 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
id object = myArray[0];// similar to [myArray objectAtIndex:0]
if(![object isEqual:[NSNull null]])
{
//do something if object is not equals to [NSNull null]
}
if (myArray != (id)[NSNull null])
또는
if(![myArray isKindOfClass:[NSNull class]])
Toni의 답변을 바탕으로 매크로를 만들었습니다.
#define isNSNull(value) [value isKindOfClass:[NSNull class]]
그런 다음 사용하려면
if (isNSNull(dict[@"key"])) ...
Awww, 여러분. 이것은 쉬운 일입니다.
// if no null values have been returned.
if ([myValue class] == [NSNull class]) {
myValue = nil;
}
더 나은 답변이 있다고 확신하지만이 방법이 작동합니다.
작업 코드에 NSNull
다음과 같은 문제가 있음을 발견했습니다 .
- 시끄럽고 못생긴 것 같습니다.
- 시간이 많이 걸립니다.
- 발생하기 쉬운 오류.
그래서 다음 카테고리를 만들었습니다.
@interface NSObject (NSNullUnwrapping)
/**
* Unwraps NSNull to nil, if the object is NSNull, otherwise returns the object.
*/
- (id)zz_valueOrNil;
@end
구현시 :
@implementation NSObject (NSNullUnwrapping)
- (id)zz_valueOrNil
{
return self;
}
@end
@implementation NSNull (NSNullUnwrapping)
- (id)zz_valueOrNil
{
return nil;
}
@end
다음 규칙에 따라 작동합니다.
- 범주가 동일한 항목
Class
(즉,Class
유형 의 단일 인스턴스)에 대해 두 번 선언되면 동작이 정의되지 않습니다. 그러나 서브 클래스에서 선언 된 메서드는 수퍼 클래스의 범주 메서드를 재정의 할 수 있습니다.
이것은 더 간결한 코드를 허용합니다 :
[site setValue:[resultSet[@"main_contact"] zz_valueOrNil] forKey:@"mainContact"];
. . 확인할 추가 줄이있는 것과는 대조적으로 NSNull
. zz_
접두사는 조금 추한 보이지만 피하기 네임 스페이스 충돌에 대한 안전을 위해 존재한다.
이미 많은 좋고 흥미로운 답변이 주어졌으며 (nealry) 모두 작동합니다.
완성을 위해서 (그리고 그것의 재미) :
[NSNull null]은 싱글 톤을 반환하도록 문서화되어 있습니다. 따라서
if (ob == [NSNull null]) {...}
너무 잘 작동합니다.
그러나 이것은 예외이므로 ==를 사용하여 객체를 비교하는 것이 일반적으로 좋은 생각이라고 생각하지 않습니다. (당신의 코드를 검토한다면, 이것에 대해 확실히 언급 할 것입니다).
In Swift (or bridging from Objective-C), it is possible to have NSNull
and nil
in an array of optionals. NSArray
s can only contain objects and will never have nil
, but may have NSNull
. A Swift array of Any?
types may contain nil
, however.
let myArray: [Any?] = [nil, NSNull()] // [nil, {{NSObject}}], or [nil, <null>]
To check against NSNull
, use is
to check an object's type. This process is the same for Swift arrays and NSArray
objects:
for obj in myArray {
if obj is NSNull {
// object is of type NSNull
} else {
// object is not of type NSNull
}
}
You can also use an if let
or guard
to check if your object can be casted to NSNull
:
guard let _ = obj as? NSNull else {
// obj is not NSNull
continue;
}
or
if let _ = obj as? NSNull {
// obj is NSNull
}
Consider this approach:
Option 1:
NSString *str = array[0];
if ( str != (id)[NSNull null] && str.length > 0 {
// you have a valid string.
}
Option 2:
NSString *str = array[0];
str = str == (id)[NSNull null]? nil : str;
if (str.length > 0) {
// you have a valid string.
}
You can use the following check:
if (myArray[0] != [NSNull null]) {
// Do your thing here
}
The reason for this can be found on Apple's official docs:
Using NSNull
The NSNull class defines a singleton object you use to represent null values in situations where nil is prohibited as a value (typically in a collection object such as an array or a dictionary).
NSNull *nullValue = [NSNull null];
NSArray *arrayWithNull = @[nullValue];
NSLog(@"arrayWithNull: %@", arrayWithNull);
// Output: "arrayWithNull: (<null>)"
It is important to appreciate that the NSNull instance is semantically different from NO or false—these both represent a logical value; the NSNull instance represents the absence of a value. The NSNull instance is semantically equivalent to nil, however it is also important to appreciate that it is not equal to nil. To test for a null object value, you must therefore make a direct object comparison.
id aValue = [arrayWithNull objectAtIndex:0];
if (aValue == nil) {
NSLog(@"equals nil");
}
else if (aValue == [NSNull null]) {
NSLog(@"equals NSNull instance");
if ([aValue isEqual:nil]) {
NSLog(@"isEqual:nil");
}
}
// Output: "equals NSNull instance"
참고URL : https://stackoverflow.com/questions/19059202/how-can-i-check-if-an-object-in-an-nsarray-is-nsnull
'development' 카테고리의 다른 글
힘내 "당신은 당신의 병합을 완료하지 않았습니다"그리고 커밋 할 것이 없습니까? (0) | 2020.11.29 |
---|---|
확장 된 메시지 / 설명이있는 Git / GitHub 커밋 (0) | 2020.11.29 |
콘솔 애플리케이션을 통한 UrlEncode? (0) | 2020.11.29 |
SQLAlchemy에서 UUID를 어떻게 사용할 수 있습니까? (0) | 2020.11.29 |
wikipedia api가있는 경우 어떻게 사용합니까? (0) | 2020.11.29 |