Explanation of Cocoa @selector usage

前端 未结 6 2052
轮回少年
轮回少年 2021-01-30 14:50

I\'m new to Cocoa/Cocoa Touch, and working through a development book. I\'ve come across situations where the @selector() operator is used. I\'m a bit lost on how and when the

相关标签:
6条回答
  • 2021-01-30 14:51

    In addition to what's been said, you can also wrap up the @selector in an NSInvocation for later use. You can set the arguments to the NSInvocation a long time after it's created, and activate it when you need the message to be fired. This gives you a lot of power.

    For an introduction to the concept, Scott Stevenson has a great post entitled "Dynamic Objective-C with NSInvocation".

    0 讨论(0)
  • 2021-01-30 14:53

    The selector operator provides a way to refer to a method provided by an object, somewhat similar to a function pointer in C. It is useful because it allows you to decouple the process of calling methods on an object. For example one piece of code could provide a method, and another piece of code could apply that method to a given set of objects.

    Examples:

    Test to see if an object implements a certain method:

    [object respondsToSelector:@selector(methodName)]
    

    Store a method to later call on an object;

    SEL method = @selector(methodName);
    [object performSelector:method];
    

    Call a method on a different thread (useful for GUI work).

    [object performSelectorOnMainThread:@selector(methodName)]
    
    0 讨论(0)
  • 2021-01-30 15:05

    @selector() is used each time you need to pass the name of a method as an argument to another method, a function or as a variable value. Passing directly the name doesn't work in objective-C.

    0 讨论(0)
  • 2021-01-30 15:10

    One reference to look at:

    http://en.wikipedia.org/wiki/Multiple_dispatch

    0 讨论(0)
  • 2021-01-30 15:14

    You can use a selector to invoke a method on an object—this provides the basis for the implementation of the target-action design pattern in Cocoa.

    [myObject performSelector:@selector(runMYmethod:) withObject:parameters];
    

    is equivalent to:

    [myObject runMYmethod:parameters];
    
    0 讨论(0)
  • 2021-01-30 15:17

    One practical example is validateMenuItem method where menu items are identified with their target actions.

    Simplified example:

    - (BOOL)validateMenuItem:(NSMenuItem *)item {
        if ([item action] == @selector(selectFiles:) && otherCondition) {
            return YES;
        } else {
            return NO;
        }
    }
    
    0 讨论(0)
提交回复
热议问题