NSManagedObject类别和委托 [英] NSManagedObject with Category and Delegate
问题描述
我创建了一个名为MapState的 NSManagedObject
。然后我创建了一个类别来调用一些方法并存储一些额外的变量。
I created a NSManagedObject
called MapState. I then created a category for it to call some methods and store some extra variables.
.h
#importMapStateDB.h
.h #import "MapStateDB.h"
@protocol MapStateDelegate;
@interface MapStateDB (MapState)
@property (weak, nonatomic) id <MapStateDelegate> delegate;
-(void)selectedSceneObject:(SceneObject *)sceneObject;
-(void)removeDisplayedScene;
@end
@protocol MapStateDelegate <NSObject>
-(void)displayScene:(SceneDB *)scene inState:(NSString *)state;
-(void)removeScene:(SceneDB *)scene;
@end
在.m:
@dynamic delegate;
-(void)setDelegate:(id<MapStateDelegate>)delegate {
}
如何做设置器?通常只是:
How do I do the setter? Normally it would just be:
-(void)setDelegate:(id<MapStateDelegate>)delegate {
_delegate = delegate;
}
但是因为变量 @dynamic
而不是 @synthesize
,不会创建 _delegate
。 @synthesize
会产生错误。
But since the variable is @dynamic
instead of @synthesize
, no _delegate
is created. And @synthesize
creates an error.
我应该如何处理?
推荐答案
使用 @dynamic
意味着将在运行时创建适当的访问器。 NSManagedObject
对数据模型中的实体的属性执行此操作,但不对您声明的属性执行此操作。您可以可以使用一些ObjC运行时语法(这些API都存在,并且是受支持的,因此它不是可以被称为黑客的),但它不是微不足道的。 (如果 delegate
是实体上的临时属性,则使用 @dynamic
会很好,但这意味着代理必须是Core Data支持的类型之一,而不是任何实现协议的类)。
Using @dynamic
implies that the appropriate accessors will be created at run time. NSManagedObject
does that for attributes of entities in the data model, but not for properties you declare. You could do this with some ObjC runtime wizardry (the APIs all exist, and are supported, so it's not what might be called a hack) but it's not trivial. (Using @dynamic
would be fine if delegate
were a transient property on the entity, but that would mean that the delegate would have to be one of the types supported by Core Data instead of any class implementing the protocol).
但是有希望!如果你使用Xcode 7+生成 NSManagedObject
子类,可以在子类中添加自己的属性,而不用担心它们被覆盖。您可以通过添加 @synthesize
为委托
工作,然后不添加自己的安装程序。
But there's hope! If you're using Xcode 7+ to generate NSManagedObject
subclasses, it's safe to add your own properties in the subclass without fear of them being overwritten. You'd make the delegate
property work by adding a @synthesize
for it and then not adding your own setter. You don't have to provide one unless you need to do more than just set the property value.
如果您请需要一个自定义安装程序,修改 @synthesize
为
If you do need a custom setter, modify the @synthesize
to be something like
@synthesize delegate = _delegate;
(您不必使用 _delegate
这里,任何有效的名称都很好)
(you don't have to use _delegate
here, any valid name is fine)
然后添加一个setter,就像你的问题中分配给合成名称的那样。
Then add a setter like the one in your question that assigns to the synthesized name.
这篇关于NSManagedObject类别和委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!