1

私は次のコード行について疑問に思っていました

[self performSelector:@selector(myMethod) withObject:self afterDelay:1.0];
[self performSelector:@selector(myMethod) withObject:nil afterDelay:1.0];
  1. 上記の2行のコードの違いは何ですか。
  2. nilオブジェクトをいつ設定する必要があり、いつオブジェクトを設定する必要がありますselfか?

ほとんどの場合、オブジェクトがとして設定されていることに気づきましたnil

4

4 に答える 4

8

リストした例では、メソッドmyMethodが引数をとらないため、異なる動作は発生しません。これが役立つのは、引数を取るメソッドがある場合です。

squareRootMethod:NSNumberを受け取り、squareRootを返すメソッドを宣言したとしましょう。それからあなたは電話します[self performSelector:@selector(squareRootMethod:) withObject:numberToRoot afterDelay:1.0]

performSelector:withObject:withObject:複数の引数を取るセレクターのようなメソッドもあります。

于 2012-06-16T14:41:48.500 に答える
3

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.

于 2012-06-16T15:21:38.270 に答える
0

最初の例では、メソッドが呼び出されたときにメソッドに渡す引数としてselfを渡しました。しかし、あなたのメソッドは引数を取らないので、それは不必要な綿毛です。

2番目の例では、を渡しnilたため、メソッドはnil存在しない引数に渡されてから終了します。これは、メソッドが引数をとらないため、「nil」という意味でより「効率的」です。オブジェクトはNULLと同等であり、通過する綿毛が少なくなり、とにかく無視されます。

于 2012-06-16T14:38:34.700 に答える
0

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.

于 2012-06-16T14:51:53.740 に答える