zoukankan      html  css  js  c++  java
  • ios- nil NULL 和 NSNull

    因为objective-c的集合对象,比如nsarray, nsdictionary, nsset等,都有可能包含nsnull对象,所以,如果以下代码中的item为nsnull,则会引起程序崩溃。

    NSString *item = [NSArray objectAtIndex:i];

    if ([item isEqualToString:@"TestNumber"]){

    //

    }

    常见的错误还有release的对象没有设置为nil,从而引起程序崩溃

    id someObject = [[Object alloc] init];

    //

    [someObject release];

    //

    if (someObject){

    //crash here

    }

    nil用来给对象赋值,NULL 则给任何指针赋值,NULL和nill不能互换,nil用于类指针赋值(在objective-c中类是一个对象),而NSNull则是用于集合操作,虽然他们表示的都是空值,但是使用的场合完全不同。所以在编码时要严格按照变量类型来赋值,将正确的空值赋值给正确的类型,使代码易于阅读和维护,也不容易引起错误。

    //判断对象不为空

    if (object) {}

    //判断对象为空

    if (object == nil) {}

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

    NSArray *pageNames = [NSArray alloc] initWithObjects:@"DocumentList", @"AdvancedSearch", @"Statistics", nil];

    //判断数组和字典元素是否为空

    UIViewController *controller = [NSArray objectAtIndex:i];

    if((NSNull *)controller == [NSNull null]){//}

    NSString *userId = [NSDictionary objectForKey:@"UserID"];

    if(userId == [NSNull null]){//}

    在objective c中当发送消息给nil对象时,系统返回0而不是引起崩溃。

  • 相关阅读:
    poj2679
    poj2709
    poj1521
    poj2054
    静脉曲张病案
    眩晕耳鸣病案
    声嘶治验
    甘露消毒丹治疗高热不退一例
    黄芩汤加减治疗腹痛一例
    自残症治愈案
  • 原文地址:https://www.cnblogs.com/lisa090818/p/3312314.html
Copyright © 2011-2022 走看看