项目进度到尾期要上线了,对于自定义头像需要做拍照截取保存功能,但是怎么样拍照后的原图都无法保存,按照常理同样的代码极难出现保存失败的情况,项目又是ex程序员交接给我的,直觉想到会是第三方的分类修改了某个implmentation.还好有万能谷歌,搜索一下果然如此
麻烦就在NSDictionary+NilSafe.h这个分类上了,仔细阅读了一下它的实现,确实是很实用,网络层数据交互的等场景对nil指针的操作变为 NSNull实例对象,不会因为NSNull出现crash,找到问题直接删除这个分类拍照保存的功能自然就实现了,但是删除了又会有很多莫名的其他crash坑等着我填,没办法只能修改这个分类了.代码如下.
在头文件增加两个类方法:
@interface NSDictionary (NilSafe)
+ (void)dcitionaryCancelNilSafe;//取消NilSafe
+ (void)reuseDictionaryNilSafe;//复用NilSafe
@end
@interface NSMutableDictionary (NilSafe)
+ (void)mutableDcitionaryCancelNilSafe;
+ (void)reuseMutableDictionaryNilSafe;
@end
具体实现如下:
+ (void)dcitionaryCancelNilSafe{
[self gl_swizzleMethod:@selector(gl_initWithObjects:forKeys:count:) withMethod:@selector(initWithObjects:forKeys:count:)];
[self gl_swizzleClassMethod:@selector(gl_dictionaryWithObjects:forKeys:count:) withMethod:@selector(dictionaryWithObjects:forKeys:count:)];
}
+ (void)reuseDictionaryNilSafe{
[self gl_swizzleMethod:@selector(initWithObjects:forKeys:count:) withMethod:@selector(gl_initWithObjects:forKeys:count:)];
[self gl_swizzleClassMethod:@selector(dictionaryWithObjects:forKeys:count:) withMethod:@selector(gl_dictionaryWithObjects:forKeys:count:)];
}
+ (void)mutableDcitionaryCancelNilSafe{
Class class = NSClassFromString(@"__NSDictionaryM");
[class gl_swizzleMethod:@selector(gl_setObject:forKey:) withMethod:@selector(setObject:forKey:)];
[class gl_swizzleMethod:@selector(gl_setObject:forKeyedSubscript:) withMethod:@selector(setObject:forKeyedSubscript:)];
}
+ (void)reuseMutableDictionaryNilSafe{
Class class = NSClassFromString(@"__NSDictionaryM");
[class gl_swizzleMethod:@selector(setObject:forKey:) withMethod:@selector(gl_setObject:forKey:)];
[class gl_swizzleMethod:@selector(setObject:forKeyedSubscript:) withMethod:@selector(gl_setObject:forKeyedSubscript:)];
}
具体的场景使用,例如在你所需要的控制器开始和结束是分类调用取消和复用方法:
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[NSDictionary dcitionaryCancelNilSafe];
[NSMutableDictionary mutableDcitionaryCancelNilSafe];
}
- (void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
[NSDictionary reuseDictionaryNilSafe];
[NSMutableDictionary reuseMutableDictionaryNilSafe];
}
这样就O98K了