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

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

问题描述

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

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

-C,当你从数据模型中生成一个 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

或者,我必须还原为具有关系的数据模型的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天全站免登陆