後臺返回null iOS

 

1。第一種解決方案  javascript

就是在每個 可能傳回null 的地方 使用  if([object isEqual:[NSNUll null]]) 去判斷html

2。第二種解決方案java

網上傳說老外寫了一個Category,叫作NullSafe..只支持到ios9,3  ,實測 並無解決個人問題..ios

NullSafe的原理見 http://www.javashuo.com/article/p-hsfhknmc-by.htmlgit

3。第三種解決方案github

 

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];json

    AFJSONResponseSerializer *serializer = [AFJSONResponseSerializer serializer];數組

    serializer.removesKeysWithNullValues = YES;網絡

    [serializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript",@"text/plain", nil]];app

    manager.responseSerializer=serializer;

    manager.requestSerializer = [AFJSONRequestSerializer serializer];

不知道爲何無效,有大神給指導一下嗎

4。第四種解決方案

json轉model時,每一個model里加上

 

- (id)valueForUndefinedKey:(NSString *)key

{

    return nil;

}

 

- (void)setValue:(id)value forUndefinedKey:(NSString *)key

{

    

}

 

5。第5種解決方案

在數組和字典的category裏面寫的兩個方法. 完美解決..在每次請求回來數據,統一處理.. 

廢話很少說,上代碼 

字典的類目:

 

#import "NSDictionary+Extension.h"

#import "NSArray+Extension.h"

@implementation NSDictionary (Extension)

- (NSDictionary *)dictionaryByReplacingNulls {

    

    const NSMutableDictionary *replaced = [self mutableCopy];

    

    const id nul = [NSNull null];

    

    for (NSString *key in self) {

        

        id object = [self objectForKey:key];

        

        if (object == nul) [replaced removeObjectForKey:key];

        

        else if ([object isKindOfClass:[NSDictionary class]]) [replaced setObject:[object dictionaryByReplacingNulls] forKey:key];

        

        else if ([object isKindOfClass:[NSArray class]]) [replaced setObject:[object arrayByReplacingNulls] forKey:key];

        

    }

    

    return [NSDictionary dictionaryWithDictionary:[replaced copy]];

    

}

@end

 

 

 

數組的類目:

 

#import "NSArray+Extension.h"

#import "NSDictionary+Extension.h"

@implementation NSArray (Extension)

- (NSArray *)arrayByReplacingNulls  {

    

    NSMutableArray *replaced = [self mutableCopy];

    

    const id nul = [NSNull null];

    

    for (int idx = 0; idx < [replaced count]; idx++) {

        

        id object = [replaced objectAtIndex:idx];

        

        if (object == nul) [replaced removeObjectAtIndex:idx];

        

        else if ([object isKindOfClass:[NSDictionary class]]) [replaced replaceObjectAtIndex:idx withObject:[object dictionaryByReplacingNulls]];

        

        else if ([object isKindOfClass:[NSArray class]]) [replaced replaceObjectAtIndex:idx withObject:[object arrayByReplacingNulls]];

        

    }

    

    return [replaced copy];

    

}

 

 

@end

 

 

在封裝的網絡請求獲取到後臺數據的地方 將數據處理一下

 

NSDictionary *dict = [responseObject dictionaryByReplacingNulls];

success(dict);

 

6。第6種解決方案 

大力推薦:

AvoidCrash不再怕程序崩潰啦 AvoidCrash的功能不單單是數組,還有報錯字典等許多功能,具體用法能夠參考https://github.com/chenfanfang/AvoidCrash

 

個人項目目前調用了3456這4種解決方案。請各位大神幫我分析利弊。

相關文章
相關標籤/搜索