繁体   English   中英

无法在具有@objc属性的协议中使用自定义类?

[英]Unable to use custom class in a protocol with @objc attribute?

我正在尝试为JSON加载委派创建一个协议, JSONLoaderDelegate 我的另一个类,称为JSONLoader ,应该将事件分派给它的委托(实现JSONLoaderDelegate协议),如:

self?.delegate?.jsonLoaderdidEndWithError(self!, error: JSONLoaderError.LoadError)

JSONLoader的实现并不重要(imho)。 但是我似乎有问题来实现协议,这是代码:

@objc protocol JSONLoaderDelegate {

    optional func jsonLoaderdidBeginLoading(jsonLoader: JSONLoader)
    func jsonLoaderdidEndWithError(jsonLoader: JSONLoader, error: JSONLoader.JSONLoaderError)
    func jsonLoaderDidEndWithSuccess(jsonLoader: JSONLoader)

}

这看起来很简单,但我收到一个错误:

方法不能标记为@objc,因为参数的类型不能用Objective-C表示。

指出了这三个功能。

显然,如果我删除@objc属性,我就不能使用函数的optional 我真的想将jsonLoaderdidBeginLoading保留为可选的。 任何想法/方法来解决这个问题? 谢谢!

我遇到了这个问题,因为我有一个没有父类的MyConnection类。 像这样。

public class MyConnection {
}

我不能把@objc放在@objc之前,因为我收到警告

只有从NSObject继承的类才能声明为@objc

所以我改变了类继承自NSObject 像这样

public class MyConnection: NSObject {
}

我有同样的错误。 method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C.

我在swift 2.0中将语法更改为以下内容。 它现在工作正常!

@objc protocol AppModelDelegate {
    optional func compititorList(com:[Competitor]!)
}

class Competitor:NSObject{
    var id:Int?
    var title:String?
}

注意:Competitor类类型已更改为NSObject,它清除了委托规则违规

同样在NSJSON解析的情况下。 我改为以下。

if (_httpStatusCode == 200) {
    let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
    var error : NSError?
    print("responseString : \(responseString) ")

    var service_result:NSDictionary =  NSDictionary()
    do {
        let anyObj = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String:AnyObject]
        service_result = anyObj
    } catch let error as ErrorType {
        print("json error: \(error)")
    }
}

3种方法的共同点是JSONLoader参数,这就是我认为阻止您桥接协议的原因。 为了解决这个问题,你必须使它与objc兼容。

JSONLoaderError.LoadError

这是枚举类型吗? 您无法将Swift枚举转换为Obj-C代码。 你需要使用int代替。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM