可可@选择器用法的说明 [英] Explanation of Cocoa @selector usage

查看:84
本文介绍了可可@选择器用法的说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Cocoa/Cocoa Touch的新手,正在研究一本开发书.我遇到了使用@selector()运算符的情况.我对如何以及何时使用@selector()运算符有些迷惑.有人可以简短简短地解释一下为什么使用它以及为开发人员带来什么好处吗?

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 @selector() operator should be used. Can someone provide a short and sweet explanation and example of why it's used and what benefit it gives the developer?

顺便说一下,这是来自使用@selector()的Apple iPhone开发站点的示例代码

By the way, here is sample code taken from Apple's iPhone development site that uses @selector()

if ([elementName isEqualToString:@"entry"])
{

    parsedEarthquakesCounter++;

    // An entry in the RSS feed represents an earthquake, so create an instance of it.
    self.currentEarthquakeObject = [[Earthquake alloc] init];
    // Add the new Earthquake object to the application's array of earthquakes.
    [(id)[[UIApplication sharedApplication] delegate]
            performSelectorOnMainThread:@selector(addToEarthquakeList:)
            withObject:self.currentEarthquakeObject waitUntilDone:YES];
    return;
}

推荐答案

选择器运算符提供了一种引用对象提供的方法的方法,该方法有点类似于C中的函数指针.它非常有用,因为它允许您执行以下操作:解耦在对象上调用方法的过程.例如,一段代码可以提供一种方法,而另一段代码可以将该方法应用于给定的一组对象.

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.

示例:

测试以查看对象是否实现某种方法:

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];

在其他线程上调用方法(对于GUI工作很有用).

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

[object performSelectorOnMainThread:@selector(methodName)]

这篇关于可可@选择器用法的说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆