Creating threads in swift?

孤街浪徒 提交于 2019-12-03 00:21:30

As of Xcode 7.3 and Swift 2.2, you can use the special form #selector(...) where Objective-C would use @selector(...):

let thread = NSThread(target:self, selector:#selector(doSomething), object:nil)

NSThread takes a selector as it's second parameter. You can describe Objective-C selectors as Strings in Swift like this:

let thread = NSThread(target: myObj, selector: "mySelector", object: nil)

Swift functions aren't equivalent objective-c methods though. If you have a method in a swift class, you can use it as a selector if you use the @objc attribute on the class:

@objc class myClass{
    func myFunc(){
    }
}

var myObj = myClass()
let thread = NSThread(target: myObj, selector: "myFunc", object: nil)
Duyen-Hoa
  1. When we call a selector on a target, we should check if the target exists and it responds to the selector. Only class that extend from NSObject or it's subclasses can use respondsToSelector:

  2. You can use a NSDictionary to store parameters if you have more than 2 parameters.

    Ex:

    //this code is in Objective-C but the same code should exist in Swift
    
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:object1, @"key1", object2, @"key2",nil]; 
    

then pass 'params' to parameter of selector:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!