NullSafe 的原理
问题场景
后端返回的数据中总会出现一些NSNull类型,当我们一处理程序就会崩溃,因此想到把返回的数据中的NSNull类型全部转换成@""空字符串
(1)原始的json串:后端返回的json串里面包含类型NSString,NSArray,NSDictionary,NSNull类型。
{"status":1,"service_name":null,"service_id":null,"img_url":"http:\/\/api.jgfw.me\/assets\/uploads\/files\/","price":null,"num":3,"service_info":{"service_type":null,"service_time":null,"service_detail":null,"customer_name":null,"customer_phone":null,"customer_address":"","new_jishi":"","old_jishi":null,"lat":null,"lon":null},"order_info":{"order_no":"E15031267469289848688","pay_time":null,"order_time":null,"price":0,"order_state":null}}
(2)用SBJson库:json串转换成字典
NSDictionary *jsonDic = [retString JSONValue];
"<null>" 就是NSNull 类型,直接使用会Crash.
摘要
NullSafe is a simple category on NSNull that returns nil for unrecognised messages instead of throwing an exception.
//
// NullSafe.m
//
// Version 1.2.2
//
// Created by Nick Lockwood on 19/12/2012.
// Copyright 2012 Charcoal Design
//
// Distributed under the permissive zlib License
// Get the latest version from here:
//
// https://github.com/nicklockwood/NullSafe
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
// //Fix issue desc = "<null>";icon = "<null>"; #import <objc/runtime.h>
#import <Foundation/Foundation.h> #ifndef NULLSAFE_ENABLED
#define NULLSAFE_ENABLED 1
#endif #pragma GCC diagnostic ignored "-Wgnu-conditional-omitted-operand" @implementation NSNull (NullSafe) #if NULLSAFE_ENABLED - (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
{
@synchronized([self class])
{
//look up method signature
NSMethodSignature *signature = [super methodSignatureForSelector:selector];
if (!signature)
{
//not supported by NSNull, search other classes
static NSMutableSet *classList = nil;
static NSMutableDictionary *signatureCache = nil;
if (signatureCache == nil)
{
classList = [[NSMutableSet alloc] init];
signatureCache = [[NSMutableDictionary alloc] init]; //get class list
int numClasses = objc_getClassList(NULL, );
Class *classes = (Class *)malloc(sizeof(Class) * (unsigned long)numClasses);
numClasses = objc_getClassList(classes, numClasses); //add to list for checking
NSMutableSet *excluded = [NSMutableSet set];
for (int i = ; i < numClasses; i++)
{
//determine if class has a superclass
Class someClass = classes[i];
Class superclass = class_getSuperclass(someClass);
while (superclass)
{
if (superclass == [NSObject class])
{
[classList addObject:someClass];
break;
}
[excluded addObject:NSStringFromClass(superclass)];
superclass = class_getSuperclass(superclass);
}
} //remove all classes that have subclasses
for (Class someClass in excluded)
{
[classList removeObject:someClass];
} //free class list
free(classes);
} //check implementation cache first
NSString *selectorString = NSStringFromSelector(selector);
signature = signatureCache[selectorString];
if (!signature)
{
//find implementation
for (Class someClass in classList)
{
if ([someClass instancesRespondToSelector:selector])
{
signature = [someClass instanceMethodSignatureForSelector:selector];
break;
}
} //cache for next time
signatureCache[selectorString] = signature ?: [NSNull null];
}
else if ([signature isKindOfClass:[NSNull class]])
{
signature = nil;
}
}
return signature;
}
} - (void)forwardInvocation:(NSInvocation *)invocation
{
invocation.target = nil;
[invocation invoke];
} #endif @end
当我们给一个NSNull对象发送消息的话,可能会崩溃(null是有内存的),而发送给nil的话,是不会崩溃的。
作者就是使用了这么一个原理,把发送给NSNull的而NSNull又无法处理的消息经过如下几步处理:
创建一个方法缓存,这个缓存会缓存项目中类的所有类名。
遍历缓存,寻找是否已经有可以执行此方法的类。
如果有的话,返回这个
NSMethodSignature
。如果没有的话,返回nil,接下来会走
forwardInvocation:
方法。[invocation invokeWithTarget:nil];
将消息转发给nil。
那么,如何判断NSNull无法处理这个消息呢,在OC中,系统如果对某个实例发送消息之后,它(及其父类)无法处理(比如,没有这个方法等),系统就会发送methodSignatureForSelector
消息,如果这个方法返回非空,那么就去执行返回的方法,如果为nil,则发送forwardInvocation
消息。
这样就完成整个转发链了。
题外话:一般来说,我们不应该在我们的项目中使用NSNull类(大部分NSNull类的来源来自于接口的返回),而使用nil,在来源上,就应该堵上(要么你解析到null进行处理,要么和你的服务端说,不要给我返回null)。
reference:
1.https://segmentfault.com/q/1010000005064181
2.https://github.com/nicklockwood/NullSafe
3.http://blog.sina.com.cn/s/blog_5c91824f0102ve3c.html
NullSafe 的原理的更多相关文章
- NSNull Crash处理 (NullSafe 的原理)
问题场景 后端返回的数据中总会出现一些NSNull类型,当我们一处理程序就会崩溃,因此想到把返回的数据中的NSNull类型全部转换成@""空字符串 (1)原始的json串:后端返回 ...
- 奇异值分解(SVD)原理与在降维中的应用
奇异值分解(Singular Value Decomposition,以下简称SVD)是在机器学习领域广泛应用的算法,它不光可以用于降维算法中的特征分解,还可以用于推荐系统,以及自然语言处理等领域.是 ...
- node.js学习(三)简单的node程序&&模块简单使用&&commonJS规范&&深入理解模块原理
一.一个简单的node程序 1.新建一个txt文件 2.修改后缀 修改之后会弹出这个,点击"是" 3.运行test.js 源文件 使用node.js运行之后的. 如果该路径下没有该 ...
- 线性判别分析LDA原理总结
在主成分分析(PCA)原理总结中,我们对降维算法PCA做了总结.这里我们就对另外一种经典的降维方法线性判别分析(Linear Discriminant Analysis, 以下简称LDA)做一个总结. ...
- [原] KVM 虚拟化原理探究(1)— overview
KVM 虚拟化原理探究- overview 标签(空格分隔): KVM 写在前面的话 本文不介绍kvm和qemu的基本安装操作,希望读者具有一定的KVM实践经验.同时希望借此系列博客,能够对KVM底层 ...
- H5单页面手势滑屏切换原理
H5单页面手势滑屏切换是采用HTML5 触摸事件(Touch) 和 CSS3动画(Transform,Transition)来实现的,效果图如下所示,本文简单说一下其实现原理和主要思路. 1.实现原理 ...
- .NET Core中间件的注册和管道的构建(1)---- 注册和构建原理
.NET Core中间件的注册和管道的构建(1)---- 注册和构建原理 0x00 问题的产生 管道是.NET Core中非常关键的一个概念,很多重要的组件都以中间件的形式存在,包括权限管理.会话管理 ...
- python自动化测试(2)-自动化基本技术原理
python自动化测试(2) 自动化基本技术原理 1 概述 在之前的文章里面提到过:做自动化的首要本领就是要会 透过现象看本质 ,落实到实际的IT工作中就是 透过界面看数据. 掌握上面的这样的本领 ...
- CRC、反码求和校验 原理分析
3月份开始从客户端转后台,算是幸运的进入全栈工程师的修炼阶段.这段时间一边是老项目的客户端加服务器两边的维护和交接,一边是新项目加加加班赶工,期间最长经历了连续工作三天只睡了四五个小时的煎熬,人生也算 ...
随机推荐
- c#中关于String、string,Object、object,Int32、int
在java中,string和String有着明显的区别,后者就是前者的一个封装.在c#中,好像是通用的,大部分情况下,两者互换并不会产生问题.今天特意查了一下资料,了解了一下两者的关系. 简单的讲,S ...
- SOCKET网络编程细节问题3
SOCKET网络编程快速上手(二)——细节问题(3) 3.SIGPIPE问题 人怕牺牲,我们写的程序也一样,人有死不瞑目,程序又何尝不是?程序跑着跑着,突然就崩掉了.好一点的牺牲前告诉你些打印,差点的 ...
- javascript拾遗
javascript中,只有null和undefined不能拥有方法,其他任何类型都可以在其上定义方法:字符串既然不是对象,怎么会有属性呢?只有引用了字符串的属性,那么javascript就会将字符串 ...
- ASP.NET MVC3开发 - CodeFisrt数据库篇之M层验证之调用远程方法(Remote)验证
本文讲述在作者在使用.net mvc3进行开发的时候用到的两种调用远程验证的方法,第一种方法比较傻瓜,第二种方法方便好用,调用远程验证是个比较常见的验证方法,比如注册用户时的用户名唯一性验证. 作者原 ...
- iOS 开发问题集锦(三)
iOS 开发问题集锦(三) 介于群里大部分童鞋都是新手,为了大家能够更好的提问,并且提的问题能更好的得到回答,下面写几点提问时的注意事项: 1.认真对待你的问题,在提问题前有过认真的思考: 2.先在 ...
- CSS:CSS学习总结
CSS:CSS学习总结 背景 CSS是一种声明式的语言,学好CSS的难度甚至大于学好一门服务器语言(我个人的感觉),这周在学习CSS,就记录一下学习经验. 1.规则声明顺序 因为CSS的样式具备层叠性 ...
- Microsoft 2013校园招聘笔试题及解答
Microsoft 2013校园招聘笔试题及解答 题目是自己做的,求讨论.吐槽.拍砖 1. Which of the following callingconvension(s) suppo ...
- [分享]CSS美化浏览器滚动条
今天看到一个站点的滚动条样式特别漂亮,顺便上网搜了一些相关资料,分享给大家: PS:兼容所有浏览器的滚动条样式目前是不存在的. IE下的滚动条样式 IE是最早提供滚动条的样式支持,好多年了,但是其它浏 ...
- Citrix 服务器虚拟化之三 Xenserver 网络管理
Citrix 服务器虚拟化之三 Xenserver 网络管理 每个Xenserver服务器都有一个或多个网络.XenServer 网络是虚拟的以太网交换机,它可以连接到外部接口(带或不带 VLAN 标 ...
- hdu1043-素数回文
http://acm.hdu.edu.cn/showproblem.php?pid=1431 整体思想可以理解为打表,可以通过如下办法打表(但是相对比较麻烦),还可以直接使用数组,将所有数据直接存储进 ...