在 Swift 中设置 NSManagedObject 关系 [英] Setting an NSManagedObject relationship in Swift

查看:15
本文介绍了在 Swift 中设置 NSManagedObject 关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将对象添加到 Swift 中 NSManagedObject 子类中的关系属性?

How does one add an object to a relationship property in an NSManagedObject subclass in Swift?

在 Objective-C 中,当您在 Xcode 中从数据模型生成 NSManagedObject 子类时,会自动生成一个包含如下声明的类扩展:

In Objective-C, when you generate an NSManagedObject subclass in Xcode from the data model, there's an automatically generated class extension which contains declarations like:

@interface MyManagedObject (CoreDataGeneratedAccessors)

     - (void)addMySubObject: (MyRelationshipObject *)value;
     - (void)addMySubObjects: (NSSet *)values;

@end

然而,Xcode 目前缺乏 Swift 类的此类生成功能.

However Xcode currently lacks this class generation capability for Swift classes.

如果我尝试直接在 Swift 对象上调用等效方法:

If I try and call equivalent methods directly on the Swift object:

myObject.addSubObject(subObject)

...我在方法调用时遇到编译器错误,因为这些生成的访问器不可见.

...I get a compiler error on the method call, because these generated accessors are not visible.

我已将关系属性声明为 @NSManaged,如文档中所述.

I've declared the relationship property as @NSManaged, as described in the documentation.

或者,对于具有关系的数据模型,我是否必须恢复为 Objective-C 对象?

Or do I have to revert to Objective-C objects for data models with relationships?

推荐答案

是的,这不再起作用了,Swift 无法在运行时以这种方式生成访问器,它会破坏类型系统.

Yeah that's not going to work anymore, Swift cannot generate accessors at runtime in this way, it would break the type system.

你需要做的是使用关键路径:

What you have to do is use the key paths:

var manyRelation = myObject.valueForKeyPath("subObjects") as NSMutableSet
manyRelation.addObject(subObject)
/* (Not tested) */

这篇关于在 Swift 中设置 NSManagedObject 关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆