NSNull Category
많은 개발 자 들 이 NSNull 에 의 해 구 속 된 적 이 있다 고 믿 습 니 다. 가장 흔히 볼 수 있 는 것 은 서버 가 돌아 온 json 입 니 다. 약속 한 사전, 배열, 숫자 입 니 다. 결 과 는 빈 값 으로 돌아 갑 니 다.
이 럴 때 NSJSONserialization 은 자동 으로 NSNull 로 바뀐다.dict [@ "hello"] 를 다시 사용 하면 exception 이 발생 하여 프로그램 이 무 너 집 니 다.
그럼 어떻게 처리 할 까요?
내 가 했 던 방법
매크로 를 써 서 되 돌아 오 는 이 클래스 가 NSNull 클래스 인지 아 닌 지 판단 합 니 다. 즉, isKindOfClass 입 니 다.
가장 간단 한 방법
다 들 아 실 거 라 고 믿 습 니 다. [NSNull null] 하나 가 아 닙 니 다.
공장 방법
단일 모드, 그러면 할당 한 이 포인터 가 [NSNull null] 인지 아 닌 지 직접 판단 하면 됩 니 다.
그럼 문제 가 생 겼 습 니 다. 컴 파일 러 에 warning 이 하나 더 생 겨 서 귀 찮 습 니 다.
... 에 있다
이 글 에는 여러 가지 방법 이 소개 되 어 있다.
- - (void)someMethod
- {
- NSString *aString = @"loremipsum";
-
- // This will complain: "Comparison of distinct pointer types ('NSString *' and 'NSNull *')"
- if (aString != [NSNull null])
- {
-
- }
-
- // This works (at least for strings), but isEqual: does different things
- // for different classes, so it's not ideal
- if ([aString isEqual:[NSNull null]])
- {
-
- }
-
- // If you cast it to the class you're comparing against
- // then you're good to go
- if (aString != (NSString *)[NSNull null])
- {
-
- }
-
- // But we can also just cast it to id and
- // that works generically
- if (aString != (id)[NSNull null])
- {
-
- }
-
- // The thing that would be really cool,
- // would be [NSNull null] returning
- // id (like in the sample category below).
- // Wouldn't count on that one though.
- if (aString != [NSNull idNull])
- {
-
- }
- }
이것들 은 모두 매우 아름 다운 해결 방안 이 아니다. 이 글 의 저 자 는 추천 했다.
- @interface NSNull (idNull)
- + (id)idNull;
- @end
- @implementation NSNull (idNull)
- + (id)idNull { return [NSNull null]; }
- @end
혹시
- if ([[NSNull null] isEqual:aString])
- {
-
- }
최종 해결 방안
위의 방법 은 모두 한 번 판단 해 야 하 는 지, 아니면 매우 우아 하지 않 은 지, 왜 일 까? 우 리 는 NULL, nil 처럼 직접 사용 할 수 없 는 지, 아니면 판단 해 야 하 는 지, 여기 서 가장 아름 다운 방법 을 추천 합 니 다.
진 항 은 하 나 를 제공 했다.
gist
나 는 나의 octopress 의 gist 플러그 인 이 끊 어 진 것 을 발견 하고 바로 붙 여 놓 았 다.
- #define NSNullObjects @[@"",@0,@{},@[]]
-
- @interface NSNull (InternalNullExtention)
- @end
-
- @implementation NSNull (InternalNullExtention)
-
- - (NSMethodSignature*)methodSignatureForSelector:(SEL)selector
- {
- NSMethodSignature* signature = [super methodSignatureForSelector:selector];
- if (!signature) {
- for (NSObject *object in NSNullObjects) {
- signature = [object methodSignatureForSelector:selector];
- if (signature) {
- break;
- }
- }
-
- }
- return signature;
- }
-
- - (void)forwardInvocation:(NSInvocation *)anInvocation
- {
- SEL aSelector = [anInvocation selector];
-
- for (NSObject *object in NSNullObjects) {
- if ([object respondsToSelector:aSelector]) {
- [anInvocation invokeWithTarget:object];
- return;
- }
- }
-
- [self doesNotRecognizeSelector:aSelector];
- }
- @end
고 급 스 럽 고 패기 있 는 방법 으로 이상 상황 을 처리 함으로써 이 기능 을 실현 한다.
여기 하나 더 제공 합 니 다.
일본 인의 포장 방안:
- #import "NSNull+OVNatural.h"
-
- @implementation NSNull (OVNatural)
- - (void)forwardInvocation:(NSInvocation *)invocation
- {
- if ([self respondsToSelector:[invocation selector]]) {
- [invocation invokeWithTarget:self];
- }
- }
-
- - (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
- {
- NSMethodSignature *sig = [[NSNull class] instanceMethodSignatureForSelector:selector];
- if(sig == nil) {
- sig = [NSMethodSignature signatureWithObjCTypes:"@^v^c"];
- }
- return sig;
- }
-
- @end
[NSMethodSignature signature WithObjCTypes: "@ ^ vc"] 의 기능 에 대해 서 는 다음 두 글 을 참고 할 수 있 습 니 다.
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html
http://nshipster.com/type-encodings/
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.