开发者

Abstracting NSManagedObject and NSDictionary

In my project I have some objects that I show from a server, lets call them Foo's. When I get my Foo feed, I parse them into a NSMutableDictionary subclass called RemoteFoo, and pass these RemoteFoo objects all around the app to display data.

If the user ends up wanting to download a RemoteFoo, I then create a core-data NSManagedObject entity called Foo, and instantiate it using the values from the RemoteFoo. All this works.

The problem I have is that If I want a method to run on a RemoteFoo and a Foo, I have to dupl开发者_开发百科icate it in both RemoteFoo.m and Foo.m. Also, my app if full of duplicate init's like:

- (id)initWithFoo:(Foo *)foo;
- (id)initWithRemoteFoo:(RemoteFoo *)foo;

How can I avoid all of this code-duplication while still separating the temporary remote RemoteFoo from the core-data Foo entities that represent the Foo the user has saved locally?


Have you thought of using something like a class cluster -

http://seanmurph.com/weblog/make-your-own-abstract-factory-class-cluster-in-objective-c/

    --------- Foo --------          NSManagedObject
    |                    |                 |
RemoteFoo             LocalFoo ------ CoreDataFoo 


You could just save all RemoteFoo's as Foo's and work with those. If you need different behavior, you could have an attribute on Foo indicating if it's remote or not.


Change your Core Data model as follow. Use one Foo instance and add a boolean attribute isRemote (or something similar) that you set by default to NO. When you download your remote objects, instantiate those as Foo managed objects and set their isRemote attribute to yes.

This way, you only need to deal with one instance in your app, while retaining the ability to clearly differentiate between local and remote Foo objects. If your app allows this you may even declare the isRemote attribute as transient, so that it will never be stored on disk, just in memory. If you do no care to persist this information, then this may be the best way to go.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜