ios – – [NSNull length]:無法識別的選擇器傳送到JSON物件
我得到一個非常奇怪的錯誤與這段程式碼:
- (NSMutableURLRequest*)setupRequestWithService:(NSString*)service andMethod:(NSString*)method { NSString* url = [NSString stringWithFormat:@"%@%@.svc/%@", serverUrl, service, method]; NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]]; // Set authentication token. NSLog(@"???????????? %@", authenticationToken); if (authenticationToken == nil) NSLog(@"NULL AUTHTOKEN"); if ([authenticationToken isEqual:[NSNull null]]) NSLog(@"NSNULL AUTHTOKEN"); if (request == nil) NSLog(@"NULL REQUEST"); [request addValue:authenticationToken forHTTPHeaderField:REQUEST_HEADER_AUTH_TOKEN]; return request; }
這是我的日誌:
???????????? <null> NSNULL AUTHTOKEN -[NSNull length]: unrecognized selector sent to instance 0x3b5a5090 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull length]: unrecognized selector sent to instance 0x3b5a5090'
看來authenticationToken是NULL.但是我不明白,如果authenticationToken為NULL,為什麼我不會在日誌上看到NULL AUTHTOKEN.
我得到這個錯誤第二次執行該方法,第一次,我沒有得到任何錯誤.這是我的日誌:
???????????? (null) NULL AUTHTOKEN
順便一提:
NSString* authenticationToken;
任何建議?
也許這裡有一個記憶體洩漏
我通過JSON直譯器對這個令人討厭使用NSNull的解決方案是在NSNull上建立一個類別,其中我定義了integerValue,floatValue,length等等 – 為所有人返回0.每次你得到另一個崩潰新增一個新的類別.當我遇到這個問題時,我覺得我有6或7歲.
沒有這樣做的問題是你必須在轉換物件的任何地方查詢NULL– 在我看來PITA.
編輯:我正在使用的程式碼,都在NSNull JSON.m檔案中:
@interface NSNull (JSON) @end @implementation NSNull (JSON) - (NSUInteger)length { return 0; } - (NSInteger)integerValue { return 0; }; - (float)floatValue { return 0; }; - (NSString *)description { return @"0(NSNull)"; } - (NSArray *)componentsSeparatedByString:(NSString *)separator { return @[]; } - (id)objectForKey:(id)key { return nil; } - (BOOL)boolValue { return NO; } @end
編輯2:現在在Swift 3:
extension NSNull { func length() -> Int { return 0 } func integerValue() -> Int { return 0 } func floatValue() -> Float { return 0 }; open override var description: String { return "0(NSNull)" } func componentsSeparatedByString(separator: String) -> [AnyObject] { return [AnyObject]() } func objectForKey(key: AnyObject) -> AnyObject? { return nil } func boolValue() -> Bool { return false } }
http://stackoverflow.com/questions/16607960/nsnull-length-unrecognized-selector-sent-to-json-objects