Swift - 如何正确使用委托

时间:2017-08-18 21:53:15

标签: ios swift salesforce-ios-sdk

我正在为我的移动应用程序使用Salesforce ios sdk,并且有一种方法可以执行SOQL查询。例如,

class SfdcController: NSObject, SFRestDelegate {   
    let request = SFRestAPI.sharedInstance().request(forQuery:"SELECT Name FROM User LIMIT 10");
    SFRestAPI.sharedInstance().send(request, delegate: self);

    func request(_ request: SFRestRequest, didLoadResponse jsonResponse: Any)
    {
        print(jsonResponse)
    }

    func request(_ request: SFRestRequest, didFailLoadWithError error: Error)
    {
       self.log(.debug, msg: "didFailLoadWithError: \(error)")
    }
}

问题 我将在同一个类中执行多个SOQL查询,并且有不同的方法来处理响应。现在,

  • 有没有办法在didLoadResponse内获取请求的引用?所以,我可以编写switch语句来执行不同的功能。
  • 如果无法重用委托,我是否需要创建多个委托类来处理每个响应?

最好的办法是什么?

更新

请求

SFRestRequest 0x1700cb130 
endpoint: /services/data 
method: GET 
path: /v39.0/sobjects/Event/describe 
queryParams: []

委托的其他方法是创建一个单独的类并定义它。

SFRestAPI.sharedInstance().send(objectDescribe, delegate: testing());


class testing: NSObject, SFRestDelegate {

    func request(_ request: SFRestRequest, didLoadResponse jsonResponse: Any) {
        print(jsonResponse)
    }
}

但是上面的问题,我每次想要执行SOQL查询时都要创建一个类。

由于

1 个答案:

答案 0 :(得分:0)

我有个你的想法。创建一个单独的委托类,并在该类中放置一个标识符。然后让这个单独的类委托给你的视图控制器。

// Create a protocol for it
class SFHandlerDelegate {
    func request(_ request: SFRestRequest, handlerId: Int, didLoadResponse jsonResponse: Any)
    func request(_ request: SFRestRequest, handlerId: Int, didFailLoadWithError error: Error)
}

创建一个新的委托类

// this becomes the SF delegate
class SFHandler : SFRestDelegate {
    var id: Int = 0
    delegate: SFHandlerDelegate
    init(id: Int, delegate: SFHandlerDelegate) { 
        self.id = id 
        self.delegate = delegate
    }

    func request(_ request: SFRestRequest, didLoadResponse jsonResponse: Any)
    {
        delegate.request(request, handlerId: id, didLoadResponse: jsonResponse)
    }

    func request(_ request: SFRestRequest, didFailLoadWithError error: Error)
    {
        delegate.request(request, handlerId: id, didFailLoadWithError: error)
    }

}

更改控制器

class SfdcController: NSObject, SFHandlerDelegate {   
    let request = SFRestAPI.sharedInstance().request(forQuery:"SELECT Name FROM User LIMIT 10");
    let delegate = SFHandlerDelegate(self, 123) // use some handler id
    SFRestAPI.sharedInstance().send(request, delegate: delegate);

    func request(_ request: SFRestRequest, handlerId: Int, didLoadResponse jsonResponse: Any)
    {
        switch handlerId {
            case 123:
                doSomething()
            // whatever
        }
        print(jsonResponse)
    }

    func request(_ request: SFRestRequest, handlerId: Int, didFailLoadWithError error: Error)
    {
         switch handlerId {
            case 123:
                doSomething()
            // whatever
         }
         self.log(.debug, msg: "didFailLoadWithError: \(error)")
    }
}