iOS-服务器返回空值处理

Github上别人写的一个Category,叫做NullSafe ,在运行时操作,把这个讨厌的空值置为nil,而nil是安全的,可以向nil对象发送任何message而不会奔溃。这个category使用起来非常 方便,只要加入到了工程中就可以了,你其他的什么都不用做,对,就是这么简单。详细的请去Github上查看;
https://github.com/nicklockwood/NullSafe

#import <objc/runtime.h>
#import <Foundation/Foundation.h>


#ifndef NULLSAFE_ENABLED
#define NULLSAFE_ENABLED 1
#endif


#pragma clang diagnostic ignored "-Wgnu-conditional-omitted-operand"


@implementation NSNull (NullSafe)

#if NULLSAFE_ENABLED

- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
{
    //look up method signature
    NSMethodSignature *signature = [super methodSignatureForSelector:selector];
    if (!signature)
    {
        for (Class someClass in @[
            [NSMutableArray class],
            [NSMutableDictionary class],
            [NSMutableString class],
            [NSNumber class],
            [NSDate class],
            [NSData class]
        ])
        {
            @try
            {
                if ([someClass instancesRespondToSelector:selector])
                {
                    signature = [someClass instanceMethodSignatureForSelector:selector];
                    break;
                }
            }
            @catch (__unused NSException *unused) {}
        }
    }
    return signature;
}

- (void)forwardInvocation:(NSInvocation *)invocation
{
    invocation.target = nil;
    [invocation invoke];
}

#endif

@end
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 做过iOS开发的,在开始的时候一定会遇到这样的问题,明明代码写的好好的,但是有时候莫名其妙的程序就崩溃了,然后下全...
    Leeson1989阅读 2,551评论 0 6
  • 在iOS开发过程中需要与服务器进行数据通讯,但是问题来了,接口返回的数据中会出现:null "<null>"等问题...
    MxlZlh阅读 2,775评论 0 5
  • 在iOS开发过程中经常需要与服务器进行数据通讯,Json就是一种常用的高效简洁的数据格式。 问题现象 但是几个项目...
    evanleeeee阅读 3,262评论 0 55
  • 某些情况下,后台可能由于各种原因,对某个字段返回了null值,这时我们取到的就是[NSNull null]这样一个...
    rectinajh阅读 2,179评论 0 1
  • 刚刚在听道子讲的关于女性能量和阴性能量,我看见自己在和老公的互动中,常常都是在使用女性能量,甚至是世俗的女性能量 ...
    金晶花阅读 1,531评论 0 0