代码之家  ›  专栏  ›  技术社区  ›  mshafrir

Cocoa@选择器使用说明

  •  24
  • mshafrir  · 技术社区  · 16 年前

    我是Cocoa/Cocoa Touch的新手,正在读一本开发书。我遇到过使用@selector()运算符的情况。我对如何以及何时使用@selector()运算符有点困惑。有人能提供一个简短而甜蜜的解释和例子,说明为什么使用它以及它给开发人员带来了什么好处吗?

    顺便说一句,这是从苹果iPhone开发网站上获取的使用@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;
    }
    
    6 回复  |  直到 16 年前
        1
  •  40
  •   Andrew Grant    16 年前

    选择器运算符提供了一种引用对象提供的方法的方法,有点类似于C中的函数指针。它很有用,因为它允许您解耦对对象调用方法的过程。例如,一段代码可以提供一个方法,而另一段代码则可以将该方法应用于给定的对象集。

    测试一个对象是否实现了某个方法:

    [object respondsToSelector:@selector(methodName)]
    

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

    [object performSelectorOnMainThread:@selector(methodName)]
    
        2
  •  4
  •   Brad Larson    16 年前

    关于这一概念的介绍,斯科特·史蒂文森有一篇很好的文章,题为 "Dynamic Objective-C with NSInvocation" .

        3
  •  2
  •   mouviciel    16 年前

    @selector() 每次需要将一个方法的名称作为参数传递给另一个方法、函数或变量值时,都会使用它。直接传递名称在objective-C中不起作用。

        4
  •  2
  •   Petteri H    15 年前

    validateMenuItem

    简化示例:

    - (BOOL)validateMenuItem:(NSMenuItem *)item {
        if ([item action] == @selector(selectFiles:) && otherCondition) {
            return YES;
        } else {
            return NO;
        }
    }
    
        6
  •  0
  •   Gajendra Rawat    11 年前

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

    [myObject runMYmethod:parameters];
    
    推荐文章