• iOS 关于nil和Nil及null与<null>的区别


      问题是这样的。

    NSDictionary *sample = [NSJSONSerialization JSONObjectWithData:received options:NSJSONReadingMutableLeaves error:&error];
    
    NSString *messageInfo = [sample objectForKey:@"message"];

    sample是一个字典,messsageInfo是从字典中根据key值取得的,然后通过log可以知道messageInfo的值为<null>。

    这时候如果需要判断其值是否为空。那么应该这么做:

    比如说这时候需要弹出一个消息框。

    if([messageInfo isEqual:[NSNull null]]){
            UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"Title" message:@"号码格式有误,请重新输入" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alter show];
        }

    iOS中nil 、NULL、 Nil 、NSNull的区别

      1.nil
      >Defines the id of a null instance.
      定义一个实例为空, 指向oc中对象的空指针。是一个对象值。
      >示例代码:
       NSString *someString = nil;
       NSURL *someURL = nil;
       id someObject = nil;
       if (anotherObject == nil) // do something

      >当对某个对象release 的同时最好把他们赋值为nil,这样可以确保安全性,如果不赋值nil,可能导致程序崩溃.
          NSArray * array = [NSArray arrayWithObjects:@"test",@"test1" ,nil];
          [array release];
          *release的同时应该将其赋值为nil

    不然对象会成为僵尸对象。
          if (array)
          {
          //仅仅对数组release,并没有赋值为nil,在程序某个地方如果继续对数组操作,程序直接崩溃
              NSString * string = [array objectAtIndex:0];
              NSLog(@"%@",string);
          }

      2. NULL: 是一个通用指针(泛型指针)

      >These macros define null values for classes and instances.
      NULL可以用在C语言的各种指针上,
      #define __DARWIN_NULL #define__DARWIN_NULLConstants

      >示例代码:
      int *pointerToInt = NULL;
      char *pointerToChar = NULL;
      struct TreeNode *rootNode = NULL;

      >在Objective-C里,nil对象被设计来跟NULL空指针关联的。他们的区别就是nil是一个对象,而NULL只是一个值。而且我们对于nil调用方法,不会产生crash或者抛出异常。

      3.Nil
      >Defines the id of a null class.
      定义一个空的类,  A null pointer to an Objective-C class。
      Available in Mac OS X v10.0 through Mac OS X v10.4.
      Declared in NSObjCRuntime.h.
      Declared Inobjc.h
      >示例代码:
      Class someClass = Nil;
      Class anotherClass = [NSString class];

      4.NSNull
      >The NSNull class defines a singleton object used to represent null values in collection objects (which don’t allow nil values).
      NSNull类定义了一个单例对象用于表示集合对象的空值

      >集合对象无法包含nil作为其具体值,如NSArray、NSSet和NSDictionary。相应地,nil值用一个特定的对象NSNull来表示。NSNull提供了一个单一实例用于表示对象属性中的的nil值。默认的实现方法中,dictionaryWithValuesForKeys:和setValuesForKeysWithDictionary:自动地将NSNull和nil相互转换,因此您的对象不需要进行NSNull的测试操作

  • 相关阅读:
    Java实现 蓝桥杯VIP 算法提高 洗牌
    判断一个窗口是否被挂起(发WM_NULL消息,或者调用IsHungAppWindow API进行测试)
    线程天敌TerminateThread与SuspendThread
    Visual C++ 异常(Exception)常见问题 (原文标题:A Visual C++ Exception FAQ)
    阻止屏保运行、显示器和系统待机(使用SystemParametersInfo和SetThreadExecutionState两种办法)
    C语言编译全过程
    MSbuild 教程
    Mac OS X下环境搭建 Sublime Text 2 环境变量配置 开发工具配置Golang (Go语言)
    grunt实用总结
    DDD(领域驱动设计)应对具体业务场景,如何聚焦 Domain Model(领域模型)?
  • 原文地址:https://www.cnblogs.com/wmx-rj/p/4761369.html
Copyright © 2020-2023  润新知