不easy查找Bug

reason: '-[__NSCFNumber rangeOfCharacterFromSet:]: unrecognized selector sent to instance   

类型转换错误:

要把NSNumber类型的转换为NSString类型的。

解决方式:

如果现有一NSNumber的变量A。要转换成NSString类型的B

方法例如以下:

NSNumberFormatter* numberFormatter = [[NSNumberFormatterallocinit];

B = [numberFormatter stringFromNumber:A];



NSDictionary初始化

Objective-C中。NSDictionary初始化的方法有非常多种

方法1: [NSDictionary dictionaryWithObjectsAndKeys:<#(id), ...#>, nil]

方法2: NSDictionary *dic = @{@"key":value}

坑在哪里?

坑就在另外一种初始化方法 NSDictionary *dic = @{@"key":value}

它究竟是怎样坑的呢?

假设你的value是为nil 必将引发崩溃:

'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]

意思就是说使用[__NSPlaceholderDictionary initWithObjects:forKeys:count:]这个初始化方法,发现keys count和objcects的个数不匹配了

怎样规避?

在使用@{@”key”:value} 这样的方式初始化的时候,一定要对value做是否为nil的推断。为nil就不要增加Dictionary

使用标准的初始化方法:

NSDictionary dictionaryWithObjectsAndKeys:value1,@"v1",value2,@"v2",value3,@"v3", nil];

或其他的几个初始化方法进行初始化。这样假设value为nil就不会增加字典。使用 objectForKey:取出来的对象就会为nil对象,不会引发崩溃。

关联:

使用@[]方法初始化NSArray也有此坑。规避方法同字典一样


原文地址:https://www.cnblogs.com/wgwyanfs/p/7389158.html