gpt4 book ai didi

ios - Swift - 如何正确使用委托(delegate)

转载 作者:行者123 更新时间:2023-11-30 12:13:18 25 4
gpt4 key购买 nike

我正在为我的移动应用程序使用 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语句来执行不同的功能。
  • 如果无法重用委托(delegate),我是否需要创建多个委托(delegate)类来处理每个响应?

更好的方法是什么?

更新

请求

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

另一种委托(delegate)方式是创建一个单独的类并定义它。

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


class testing: NSObject, SFRestDelegate {

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

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

谢谢

最佳答案

我有一个主意给你。创建一个单独的委托(delegate)类并在该类中放置一个标识符。然后让该单独的类委托(delegate)返回到您的 View Controller 。

// 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)
}

创建一个新的委托(delegate)类

// 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)
}

}

更换 Controller

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)")
}
}

关于ios - Swift - 如何正确使用委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45765501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com