• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Swift里performSelector方法的替代

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

最近在回答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

方法二:

可以使用NSThread.detachNewThreadSelector,好处是可以使用延迟,并且可以附带object,下面是掩饰代码:

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let delay = 2.0 * Double(NSEC_PER_SEC)
        var time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
        dispatch_after(time, dispatch_get_main_queue(), {
            NSThread.detachNewThreadSelector(Selector("greetings:"), toTarget:self, withObject: "sunshine")
        })
    }
    
    func greetings(object: AnyObject?) {
        println("greetings world")
        println("attached object: \(object)")
    }
    
}

方法三:

使用NSTimer:

class func scheduledTimerWithTimeInterval(_ seconds: NSTimeInterval,
                                      target target: AnyObject!,
                                 selector aSelector: Selector,
                                  userInfo userInfo: AnyObject!,
                                    repeats repeats: Bool) -> NSTimer!

  

Xcode 6 Beta2

另外请参考一篇不错的文章:初探swift语言的学习笔记十一(performSelector)

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

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Swift基本语法以及与OC的比较发布时间:2022-07-13
下一篇:
swift不同地方 命名空间module iOS发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap