ios开发--判断是否为空

来源:互联网 发布:java wmf转jpg 编辑:程序博客网 时间:2024/05/16 17:30

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.nilNULLNSNull 的使用

nil用来给对象赋值(Objective-C中的任何对象都属于id类型),NULL则给任何指针赋值,NULLnil不能互换,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]) {  

}  

0 0
原创粉丝点击