NSManagedObject with Category and Delegate

给你一囗甜甜゛ 提交于 2019-12-12 01:28:53

问题


I created a NSManagedObject called MapState. I then created a category for it to call some methods and store some extra variables.

.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

In the .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;
}

But since the variable is @dynamic instead of @synthesize, no _delegate is created. And @synthesize creates an error.

How should I be handling this?


回答1:


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).

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.

If you do need a custom setter, modify the @synthesize to be something like

@synthesize delegate = _delegate;

(you don't have to use _delegate here, any valid name is fine)

Then add a setter like the one in your question that assigns to the synthesized name.



来源:https://stackoverflow.com/questions/33831000/nsmanagedobject-with-category-and-delegate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!