zoukankan      html  css  js  c++  java
  • 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的测试操作

  • 相关阅读:
    centOS7虚拟机连接大网
    [CSP-S模拟测试48]反思+题解
    [CSP-S模拟测试47]反思+题解
    [bzoj2456]mode 题解
    [CSP-S模拟测试45]题解
    [CSP模拟测试43、44]题解
    [CSP-S模拟测试41]题解
    [NOIP模拟测试38]题解
    一些idea
    [NOIP模拟测试37]反思+题解
  • 原文地址:https://www.cnblogs.com/wmx-rj/p/4761369.html
Copyright © 2011-2022 走看看