項(xiàng)目進(jìn)度到尾期要上線了,對(duì)于自定義頭像需要做拍照截取保存功能,但是怎么樣拍照后的原圖都無(wú)法保存,按照常理同樣的代碼極難出現(xiàn)保存失敗的情況,項(xiàng)目又是ex程序員交接給我的,直覺(jué)想到會(huì)是第三方的分類修改了某個(gè)implmentation.還好有萬(wàn)能谷歌,搜索一下果然如此
麻煩就在NSDictionary+NilSafe.h這個(gè)分類上了,仔細(xì)閱讀了一下它的實(shí)現(xiàn),確實(shí)是很實(shí)用,網(wǎng)絡(luò)層數(shù)據(jù)交互的等場(chǎng)景對(duì)nil指針的操作變?yōu)?NSNull實(shí)例對(duì)象,不會(huì)因?yàn)镹SNull出現(xiàn)crash,找到問(wèn)題直接刪除這個(gè)分類拍照保存的功能自然就實(shí)現(xiàn)了,但是刪除了又會(huì)有很多莫名的其他crash坑等著我填,沒(méi)辦法只能修改這個(gè)分類了.代碼如下.
在頭文件增加兩個(gè)類方法:
@interface NSDictionary (NilSafe)
+ (void)dcitionaryCancelNilSafe;//取消NilSafe
+ (void)reuseDictionaryNilSafe;//復(fù)用NilSafe
@end
@interface NSMutableDictionary (NilSafe)
+ (void)mutableDcitionaryCancelNilSafe;
+ (void)reuseMutableDictionaryNilSafe;
@end
具體實(shí)現(xiàn)如下:
+ (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:)];
}
具體的場(chǎng)景使用,例如在你所需要的控制器開(kāi)始和結(jié)束是分類調(diào)用取消和復(fù)用方法:
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[NSDictionary dcitionaryCancelNilSafe];
[NSMutableDictionary mutableDcitionaryCancelNilSafe];
}
- (void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
[NSDictionary reuseDictionaryNilSafe];
[NSMutableDictionary reuseMutableDictionaryNilSafe];
}
這樣就O98K了