NSNULL은 내 init와 함께 충돌합니다
-
05-07-2019 - |
문제
JSON 파일을 구문 분석하고 있습니다.
nsDictionary를 얻은 후 사전의 개체를 다양한 객체에 구문 분석합니다. 그러나 특정 JSON 파일의 경우 NULL이 발생하지만 괜찮을 것입니다. 그러나 무언가를 기대하고 있지만 NULL을 얻는 곳에서 앱이 충돌합니다.
- (id)initWithDictionary:(NSDictionary *)boxDictionary {
if ([self init]) {
// ...
int numberOfBoxes = [[boxDictionary valueForKey:@"box_count"] intValue];
int numberOfItemsInBoxes = [[boxDictionary valueForKey:@"box_items_count"] intValue];
// ..
}
return self;
}
해결책
기본적인 문제는 NSNULL에 valueForKey로 돌아 오는 NSNULL에 대한 IntValue 메소드가 없다는 것 같습니다.
intvalue 메소드를 추가 할 수 있지만 NSNULL에 대해 무엇을 반환 할 수 있습니까? 0? -1?
그렇게하는 코드는 다음과 같이 보일 것입니다.
mynullextensions.h :
@interface NSNull (integer)
-(int) intValue;
@end
그리고 mynullextensions.m :
#import "MyNullExtensions.h"
@implementation NSNull (functional)
-(int) intValue
{
return -1;
}
@end
나중에 블레이크.
다른 팁
an int
수 없습니다 nil
, 그래서 intValue
그것을 얻을 수 없다고 말할 방법이 없습니다. intValue
a nil
물체. 당신은 당신이 객체를 가지고있는 것을 확인해야합니다. valueForKey:
당신이 그것을 요청하기 전에 intValue
.
if ([boxDictionary valueForKey:@"box_count"])
numberOfBoxes = [[boxDictionary valueForKey:@"box_count"] intValue];
intvalue를 호출하기 전에 NSNULL에 대한 간단한 테스트 만하면됩니다. NSNULL 객체를 확장 할 필요가 없습니다.
if ([rate valueForKey:@"value"]!=[NSNull alloc]) {
// put your code here
}
제휴하지 않습니다 StackOverflow