Question

I have been wondering about the following lines of code

[self performSelector:@selector(myMethod) withObject:self afterDelay:1.0];
[self performSelector:@selector(myMethod) withObject:nil afterDelay:1.0];
  1. Whats the difference between the above 2 lines of code.
  2. When should we set object as nil and when should we set object as self?

In most cases I have noticed the object to be set as nil.

Was it helpful?

Solution

The difference is whether or not you are passing an object to the selector. All the selector is doing is describing a method.

[self performSelector:@selector(myMethod) withObject:nil afterDelay:1.0];

is different from:

[self performSelector:@selector(myMethod:usingThis:) withObject:nil afterDelay:1.0];

Now if you want the selector (i.e. method) to work on some object that you pass in, say an Array, Dictionary, or class. You use withObject. As in:

[self performSelector:@selector(myMethod:) withObject:myDictionary afterDelay:1.0];

-(void)myMethod:(NSDictionary*)dictionary
{
// Do something with object
}

You could pass in anything including a reference to the current class (e.g. self), as you did in your example.

OTHER TIPS

In the example you listed you won't experience any different behavior because your method myMethod takes no arguments. Where this is useful, is when you have a method that takes arguments.

Let's say we declared a method, squareRootMethod: that takes a NSNumber and returns the squareRoot. Then you would call [self performSelector:@selector(squareRootMethod:) withObject:numberToRoot afterDelay:1.0]

There are also methods like performSelector:withObject:withObject: for selectors that take more than one argument.

Notice the difference between these two:

@selector(myMethod)
@selector(myMethod:)

The first one is a method that doesn't take any parameters, the second is a method that takes one parameter. The withObject: part of the performSelector: method you're using allows you to pass an object into the method when it is called. However, in the case where the method doesn't take any parameters it doesn't matter because it won't be used.

In the first example, you passed self as the argument to pass to the method when it is invoked. But your method takes no arguments, so it is unnecessary fluff.

In the second example, you passed nil, so the method is passed nil to it's non-existent arguments and then terminates. This is more "efficient" in the sense that because your method takes no arguments, and `nil. Is the object equivalent of NULL, then you pass less fluff through that is ignored anyhow.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top