我需要一个NSManagedObject和一个常规NSObject的共享接口。在Objective-c中,我可以使用协议来实现这一点。但是在Swift中我得到了这个运行时错误。任何方案?提前谢谢!
protocol Product {
var code: String { get set }
var sp: String { get set }
}
class Stock: NSManagedObject, Product {
@NSManaged var code: String
@NSManaged var sp: String
}
错误:架构i386的未定义符号: “__TFC11YellowPages5Stockg2spSS”,引自: Stock.o中的__TFC11YellowPages5Stockm2spSS “__TFC11YellowPages5Stockg4codeSS”,引自: Stock.o中的__TFC11YellowPages5Stockm4codeSS ld:找不到架构i386的符号 clang:错误:链接器命令失败,退出代码为1(使用-v查看调用)
答案 0 :(得分:6)
这对我有用。亲自尝试一下,看看它是否有效:
class MyEntity: NSManagedObject {
@NSManaged var testAttribute: String
}
@objc
protocol MyProtocol {
var testAttribute: String { get set }
}
extension MyEntity: MyProtocol { }
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let myContext = appDelegate.managedObjectContext!
let entity: MyEntity = NSEntityDescription.insertNewObjectForEntityForName("MyEntity", inManagedObjectContext: myContext) as MyEntity
foo(entity)
println(entity.testAttribute)
}
func foo(var object: MyProtocol) {
object.testAttribute = "bar"
}
}
以下也有效,但我认为以上是更好的方法:
@objc
protocol MyProtocol {
var testAttribute: String { get set }
}
class MyEntity: NSManagedObject, MyProtocol {
@NSManaged var testAttribute: String
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let myContext = appDelegate.managedObjectContext!
let entity: MyEntity = NSEntityDescription.insertNewObjectForEntityForName("MyEntity", inManagedObjectContext: myContext) as MyEntity
foo(entity)
println(entity.testAttribute)
}
func foo(var object: MyProtocol) {
object.testAttribute = "bar"
}
}
答案 1 :(得分:0)
快速
使用动态修饰符标记成员声明时,访问 始终使用Objective-C动态调度该成员 运行。编译器从不内联或取消虚拟化对该成员的访问。
class Stock: NSManagedObject, Product {
@NSManaged dynamic var code: String
@NSManaged dynamic var sp: String
}
有关此here
的更多信息