您的位置:首页 > 移动开发 > IOS开发

ios开发--判断是否为空

2015-11-18 10:19 387 查看
1.字符串判空

- (BOOL) isBlankString:(NSString *)string {

    if (string == nil || string == NULL) {

        return YES;

    }

    if ([string isKindOfClass:[NSNull class]]) {

        return YES;

    }

    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {

        return YES;

    }

    return NO;



 

2.nil、NULL和NSNull 的使用

nil用来给对象赋值(Objective-C中的任何对象都属于id类型),NULL则给任何指针赋值,NULL和nil不能互换,nil用于类指针赋值(在Objective-C中类是一个对象,是类的meta-class的实例), 而NSNull则用于集合操作,虽然它们表示的都是空值,但使用的场合完全不同。

示例如下:

id object = nil;  

// 判断对象不为空  

if (object) {  

}  

      

// 判断对象为空  

if (object == nil) {  

}  

          

// 数组初始化,空值结束  

NSArray *array = [[NSArray alloc] initWithObjects:@"First", @"Second", nil];  

  

// 判断数组元素是否为空  

NSString *element = [array objectAtIndex:2];  

if ((NSNull *)element == [NSNull null]) {  

}  

  

// 判断字典对象的元素是否为空  

NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:  

    @"iPhone", @"First", @"iPad", @"Second", nil];  

NSString *value = [dictionary objectForKey:@"First"];  

if ((NSNull *)value == [NSNull null]) {  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: