空值(nil值)导致的app崩溃
1、问题描述
有下面一段代码:
+ (NSString *)filterContentXml:(NSString *)contentXml
{
NSString * str = [NSString stringWithString:contentXml]; ——contentXml为nil时,必现崩溃。。。。
str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@"\r\n"];
str = [str stringByReplacingOccurrencesOfString:@"<br>" withString:@"\r\n"];
str = [str stringByReplacingOccurrencesOfString:@"\r" withString:@" "];
.......
return str;
}
崩溃日志一般如下:
>>17:13:00.464188 [fatal] <app_except> CRASH: *** -[NSPlaceholderString initWithString:]: nil argument
Stack Trace: (
0 CoreFoundation 0x234c1f9f <redacted> + 150
1 libobjc.A.dylib 0x30c20c77 objc_exception_throw + 38
2 CoreFoundation 0x234c1ecd <redacted> + 0
3 Foundation 0x241225b7 <redacted> + 90
4 Foundation 0x24127923 <redacted> + 42
5 EnterpriseSM 0x001ecd1d +[NewsXmlParser filterContentXml:] + 80
6 EnterpriseSM 0x0059b07d -[ReportScrollViewController splitContent] + 484
7 EnterpriseSM 0x0059a7ab -[ReportScrollViewController textToSpeak] + 126
8 EnterpriseSM 0x00698675 -[SoundButton onAction:] + 776
9 UIKit 0x26971497 <redacted> + 70
10 UIKit 0x26971439 <redacted> + 44
11 UIKit 0x2695c04d <redacted> + 584
12 UIKit 0x26970e69 <redacted> + 584
13 UIKit 0x26935ca7 <redacted> + 10158
14 CoreFoundation 0x23488845 <redacted> + 20
15 CoreFoundation 0x23485f29 <redacted> + 276
16 CoreFoundation 0x2348632b <redacted> + 914
17 CoreFoundation 0x233d3db1 CFRunLoopRunSpecific + 476
18 CoreFoundation 0x233d3bc3 CFRunLoopRunInMode + 106
19 GraphicsServices 0x2a75f051 GSEventRunModal + 136
20 UIKit 0x2699fa31 UIApplicationMain + 1440
21 EnterpriseSM 0x0053df4d main + 116
22 libdyld.dylib 0x311bcaaf <redacted> + 2
) - UnCaughtExceptionHandlerForWind.m:28
2014-10-22 17:13:01.473 EnterpriseSM[203:9341] *** Terminating app due to uncaught exception 'NSInvalidArgumentException',reason: '*** -[NSPlaceholderString initWithString:]: nil argument'
*** First throw call stack:
(0x234c1f87 0x30c20c77 0x234c1ecd 0x241225b7 0x24127923 0x1ecd1d 0x59b07d 0x59a7ab 0x698675 0x26971497 0x26971439 0x2695c04d 0x26970e69 0x26935ca7 0x23488845 0x23485f29 0x2348632b 0x233d3db1 0x233d3bc3 0x2a75f051 0x2699fa31 0x53df4d 0x311bcaaf)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
2、问题分析以及参考解决方案
此种需要根据具体场景,进行空值保护。针对以上代码,修改如下:
+ (NSString *)filterContentXml:(NSString *)contentXml
{
NSString * str = nil;
if (contentXml != nil)
{
str = [NSString stringWithString:contentXml];
str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@"\r\n\r\n"];
str = [str stringByReplacingOccurrencesOfString:@"<br>" withString:@"\r\n"];
str = [str stringByReplacingOccurrencesOfString:@"\r" withString:@" "];
......
}
return str;
}
3、总结
此类bug是iOS开发中最为常见的bug之一,基本都是开发者粗心大意、不够细心导致。
4、参考资料
暂无。