Swift - 传递对类的引用

时间:2015-10-26 22:03:26

标签: swift2

我有一个将执行搜索的课程。一旦完成,我希望搜索类将结果传回到(另一个类)实例开始搜索的结果。我的想法是传递对实例化搜索类的类的引用,并使用该引用来调用函数。这是我正在尝试做的一个基本的例子。我怎样才能使这个工作起作用,或者有其他/更好的方法吗?

Search Class(我尝试过AnyObject和UITableViewContoller):

class SearchClass : NSObject, NSURLConnectionDelegate, NSURLConnectionDataDelegate {
    var callingClass : AnyObject? = nil //To store reference to the "other" class
    var searchResults : [[String : AnyObject]]? = nil

    init(callingClass: AnyObject) { //I don't know the name of the ViewController class which will instantiates this as it will be called by several different classes
        self.callingClass = callingClass
    }

    func startSearch(searchString: String) {
        //NSURLConnection etc
    }

    func connectionDidFinishLoading(connection: NSURLConnection) {
        //more code
        searchResults = ...
        callingClass!.searchCompleted(searchResults) //Pass the search results back to the class instance which started the search  
    }
}

其他课程:

class RandomViewController : UITableViewController {

    //The casting on the next line fails
    let Searcher = SearchClass(callingClass: self as! UITableViewController) //OR AnyObject

    func randomFunction() {
        searcher.startSearch("search query")
    }

    func searchComplete(searchResults: [[String : AnyObject]]) {
        self.searchResults = searchResults
        tableView.reloadData()
    }
}

2 个答案:

答案 0 :(得分:1)

您可以在搜索类中的startSearch函数中添加闭包参数:

typealias SearchResultHandler = (result: [String : AnyObject]) -> ()

func startSearch(query: String, resultHandler: SearchResultHandler) {
    // send the search request and in the completion handler of the request call your result handler:
    resultHandler(result: searchResult)
}

然后你可以从任何一个班级打电话:

let searcher = SearchClass()
searcher.startSearch("query") { (result) -> () in
    self.searchResults = results
    tableView.reloadData()
}

答案 1 :(得分:0)

当您不知道该课程的内容时,您可以使用泛型:

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html

<强>然而....

这似乎是你应该使用协议/代理的东西。

// NOTE: weak references must be class type
protocol SearchClassDelegate: class {
    func searchComplete(results: [[String: AnyObject]?])
}

// This is where you define T as the generic class
class SearchClass {

    weak var delegate: SearchClassDelegate? // This is your "callingClass"
    // NOTE: make sure it's weak

    // ...

    func connectionDidFinishLoading() {
        // ...
        self.delegate?.searchComplete(results)
    }
}

// Set to the delegate
class ViewController: UIViewController, SearchClassDelegate {

    // ...
    // Make sure you set the delegate

    // Here is where you implement this function
    func searchComplete(results: [[String : AnyObject]?]) {
        // Do whatever
        // ...reloadData() etc.
    }

}