gpt4 book ai didi

ios - NSManagedObject 不能符合 Swift 中的协议(protocol)

转载 作者:IT王子 更新时间:2023-10-29 05:51:39 25 4
gpt4 key购买 nike

我需要一个 NSManagedObject 和一个常规 NSObject 的共享接口(interface)。在 Objective-c 中,我可以使用一个协议(protocol)来实现它。但是在 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
}

Error: Undefined symbols for architecture i386:"__TFC11YellowPages5Stockg2spSS", referenced from:__TFC11YellowPages5Stockm2spSS in Stock.o"__TFC11YellowPages5Stockg4codeSS", referenced from:__TFC11YellowPages5Stockm4codeSS in Stock.old: symbol(s) not found for architecture i386clang: error: linker command failed with exit code 1 (use -v to see invocation)

最佳答案

这对我有用。亲自尝试一下,看看是否有效:

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

关于ios - NSManagedObject 不能符合 Swift 中的协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27203722/

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