iOS开发 字符串判空解决-[__NSCFNumber length]: unrecognized selector sent to instance的问题

最近手上的OC项目,我增加了对字符串length来判空的处理,发现对一些id转换成字符串的模型出现了崩溃.对id判空时出现了-[__NSCFNumber length]: unrecognized selector sent to instance的问题.找了一下,是由于其他类型赋值为NSString类型导致的问题.因此,在使用length判空前需要用stringWithFormat先转化一下.最好的字符串判空代码如下:

//字符串判空方法,YES是空字符串
+ (BOOL)isBlankString:(NSString *)aStr {
    if (!aStr) {
        return YES;
    }
    if ([aStr isKindOfClass:[NSNull class]]) {
        return YES;
    }
    //下面一句代码可以避免其他类型赋值为NSString,导致'-[__NSCFNumber length]: unrecognized selector sent to instance’的问题
    aStr = [NSString stringWithFormat:@"%@",aStr];
    if (!aStr.length) {
        return YES;
    }
    NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *trimmedStr = [aStr stringByTrimmingCharactersInSet:set];
    if (!trimmedStr.length) {
        return YES;
    }
    return NO;
}

数组和字典判空代码如下:

//NSDictionary字典 判空处理.YES就是空
+ (BOOL)isNullToDictionary:(NSDictionary *)dict {
    if (dict != nil && ![dict isKindOfClass:[NSNull class]] && dict.count != 0){
        return NO;
    }else{
        return YES;
    }
}

//NSArray数组判空处理,YES就是空
+ (BOOL)isNullToArray:(NSArray *)array {
    if (array != nil && ![array isKindOfClass:[NSNull class]] && array.count != 0){
        return NO;
    }else{
        return YES;
    }
}

你可能感兴趣的:(iOS开发 字符串判空解决-[__NSCFNumber length]: unrecognized selector sent to instance的问题)