When to use a colon with a @selector

前端 未结 6 1229
傲寒
傲寒 2020-12-03 04:10

Just getting going with iPhone development and Objective-C.

Yesterday I was trying to addObserver for a notification in a view of mine, and I kept getti

6条回答
  •  庸人自扰
    2020-12-03 04:29

    A selector represents a method name, and the number of colons in a selector matches the number of arguments in the corresponding method:

    1. mySelector — no colon, no arguments, e.g. - (void)mySelector;, [self mySelector];
    2. mySelectorWithFoo: — one colon, a single argument, e.g. - (void)mySelectorWithFoo:(Foo *)foo;, [self mySelectorWithFoo:someFoo];
    3. mySelectorWithFoo:withBar: — two colons, two arguments, e.g. - (void)mySelectorWithFoo:(Foo *)foo bar:(Bar *)bar;, [self mySelectorWithFoo:someFoo bar:someBar];

    and so forth.

    It is also possible to have a selector without ‘naming’ the parameters. It’s not recommended since it’s not immediately clear what the parameters are:

    1. mySelector:: — two colons, two arguments, e.g. - (void)mySelector:(Foo *)foo :(Bar *)bar;, [self mySelector:someFoo :someBar];
    2. mySelector::: — three colons, three arguments, e.g. - (void)mySelector:(int)x :(int)y :(int)z;, [self mySelector:2 :3 :5];

提交回复
热议问题