Swift裡performSelector方法的替代

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   strong   

最近在回答StackOverflow的問題時,發現performSelector方法在Swift被去掉,Apple的注釋是這個方法被去掉是因為不安全:

NOTEThe 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 UIKitclass 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 UIKitclass 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,希望這個方法不會近期被去掉。 

Yang Zhou
出處:http://yangzhou1030.cnblogs.com
本文著作權歸作者和部落格園共有,未經作者同意禁止轉載,作者保留追究法律責任的權利。請在文章頁面明顯位置給出原文串連,作者保留追究法律責任的權利。
相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.