-[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]

iOS中我们经常会对 Dictionary 进行初始化操作,有时我们对一些传参的 key 或者 ValueDictionary 进行初始化时,会忘记进行判断!然后当为空时奔溃发生了!我们先看两个简单的初始化代码:

//key 为空
    NSString *t = nil;
    NSDictionary *dic = @{t:@"Test"};

// value 为空
    NSString *t = nil;
    NSDictionary *dic = @{@"Test":t};

//运行奔溃报告
 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]'

看到这,你还会对那些感觉一定不会为空的代码自信满满么!如果多写一行判断或者多写一行 NSAssert 呢!

    NSString *t = nil;
    if (!t) {
        //do something!
    }
    NSAssert(t != nil, @"Initial dictionary key or value can't is nil");
    NSDictionary *dic = @{@"111":t};

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

推荐阅读更多精彩内容