使用withObject:self和withObject:nil之间的区别

Jea*_*ott 1 iphone objective-c ios performselector

我一直想知道以下几行代码

[self performSelector:@selector(myMethod) withObject:self afterDelay:1.0];
[self performSelector:@selector(myMethod) withObject:nil afterDelay:1.0];
Run Code Online (Sandbox Code Playgroud)
  1. 什么是上面两行代码之间的区别.
  2. 什么时候我们应该设置对象作为nil何时将对象设置为self

在大多数情况下,我注意到要设置的对象nil.

Mik*_*e Z 8

在您列出的示例中,您将不会遇到任何不同的行为,因为您的方法myMethod不带参数.这有用的地方,就是你有一个带参数的方法.

假设我们声明了一个方法,squareRootMethod:它接受一个NSNumber并返回squareRoot.然后你会打电话[self performSelector:@selector(squareRootMethod:) withObject:numberToRoot afterDelay:1.0]

还有一些方法,比如performSelector:withObject:withObject:选择器采用多个参数.

  • [performSelector:withObject:withObject:](https://developer.apple.com/library/ios/DOCUMENTATION/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/doc/uid/20000052 -BBCGGCBE) (4认同)