Explanation of Cocoa @selector usage

前端 未结 6 2050
轮回少年
轮回少年 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: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)]
    

提交回复
热议问题