码迷,mamicode.com
首页 > 其他好文 > 详细

Swift里performSelector方法的替代

时间:2014-07-08 22:07:46      阅读:278      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   strong   

最近在回答StackOverflow的问题时,发现performSelector方法在Swift被去掉,Apple的注释是这个方法被去掉是因为不安全:

NOTE
The performSelector: method and related selector-invoking methods are not imported in Swift because they are inherently unsafe.

如果在Swift调用这个方法会编译出错:

‘performSelector‘ is unavailable: ‘performSelector‘ methods are unavailable

反复尝试后,我发现可以使用 UIControl

func sendAction(_ action: Selector, to target: AnyObject!, forEvent event: UIEvent!)

下面是一段演示代码:

import UIKit

class ViewController: UIViewController {
                            
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        var control:UIControl = UIControl()
        control.sendAction(Selector("greetings"), to: self, forEvent: nil)
    }
    
    func greetings() {
        println("greetings world")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Log打印出:

greetings world

如果是Swift调用Objective-C类的target和action,可以参考下面的例子,假设有TestClass是Objective-C类,并且有getBarButtonItem返回UIBarButtonItem:

#import "TestClass.h"

@implementation TestClass

- (UIBarButtonItem *)getBarButtonItem
{
    UIBarButtonItem *bar = [[UIBarButtonItem alloc] init];
    bar.target = self;
    bar.action = @selector(help);
    return bar;
}

- (void)help
{
    NSLog(@"Help offered");
}

@end

那么在Swift里可以用下面的代码执行help方法:

import UIKit

class ViewController: UIViewController {
                            
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        var testClass = TestClass()
        var button: UIButton = UIButton()
        var barButtonItem = testClass.getBarButtonItem()
        button.sendAction(barButtonItem.action, to: barButtonItem.target, forEvent: nil)
    }
    
}

Log打印出:

2014-07-06 23:49:49.942 TestApp [53986:2552835] Help offered

我使用的是Xcode 6 Beta2,希望这个方法不会近期被去掉。 

bubuko.com,布布扣
作者:Yang Zhou
出处:http://yangzhou1030.cnblogs.com
本文版权归作者和博客园共有,未经作者同意禁止转载,作者保留追究法律责任的权利。请在文章页面明显位置给出原文连接,作者保留追究法律责任的权利。

Swift里performSelector方法的替代,布布扣,bubuko.com

Swift里performSelector方法的替代

标签:style   blog   http   color   使用   strong   

原文地址:http://www.cnblogs.com/yangzhou1030/p/3830592.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!