NSObject相关概念说明

230 阅读2分钟

##1.野指针与僵尸对象

野指针

C语言:        当我们声明1个指针变量,没有为这个指针变量赋初始值.这个指针变量的值是1个垃圾指指针,指向1块随机的内存空间。

OC语言:         指针指向的对象已经被回收掉了。这个指针就叫做野指针。

僵尸对象

1个已经被释放的对象 就叫做僵尸对象.

##2.nil/Nil/NULL/NSNull的区别 nil:指向oc中对象的空指针

    Nil:指向oc中类的空指针

    NULL:指向其他类型的空指针,如一个c类型的内存指针

    NSNull:在集合对象中,表示空值的对象

    若obj为nil:         [obj message]将返回NO,而不是NSException

    若obj为NSNull:        [obj message]将抛出异常NSException

        nil和NULL从字面意思来理解比较简单,nil是一个对象,而NULL是一个值,我的理解为nil是将对象设置为空,而NULL是将基本类型设置为空的。而且我们对于nil调用方法,不会产生crash或者抛出异常。

使用方法: NSURL *url = nil; Class class = Nil; int *pointerInt = NULL; nil是一个对象指针为空,Nil是一个类指针为空,NULL是基本数据类型为空。

##3.延迟执行函数和取消延时执行函数 NSObject 的系统分类方法

  • (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay inModes:(NSArray *)modes;
  • (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay;
  • (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget selector:(SEL)aSelector object:(id)anArgument;
  • (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget;

当执行一个带有参数的延时函数时,如果想取消延时则必须带上相同的参数,否则无法取消;

开始执行: [self performSelector:@selector(delayAction:) withObject:[NSNumber numberWithBool:YES] afterDelay:3.0f];

[self performSelector:@selector(delayActionNoArgument) withObject:nil afterDelay:3.0f];

取消执行: [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayAction:) object:[NSNumber numberWithBool:YES]];//可以取消成功。

[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayAction:) object:[NSNumber numberWithBool:NO]];//不能取消成功。参数不匹配

[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayAction:) object:nil];//不能取消成功。参数不匹配

[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayActionNoArgument) object:nil];//可以成功取消

[NSObject cancelPreviousPerformRequestsWithTarget:self];//可以成功取消全部。
[[self class] cancelPreviousPerformRequestsWithTarget:self];//可以成功取消全部。