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

标签 ios swift

我需要一个 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.o ld: symbol(s) not found for architecture i386 clang: 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/

相关文章:

ios - 在 SwiftUI 中启动屏幕图像拉伸(stretch)

swift - 带有 SegmentControl Swift 3 的 ActionSheet

ios - swift 3 此类对于键 startDate 不符合键值编码

ios - 检查IOS中的日期是否正确

ios - 将图标添加到 SBSearchTableViewCell

ios - 如何在屏幕中央呈现按钮?

ios - 如何更改 UISegmentedControl 的高度?

iphone - 在 iOS 6 中以编程方式获取通话记录

arrays - 如何快速计算数组中的特定项目

swift - SpriteKit 游戏中的高 CPU 使用率