开发者

Implementation help... Subclass NSManagedObject?

I'm working on an app where I have some products that I download in a list. The downloaded products are displayed in a table and each will is showing a detail view with more information.

These same products can be saved as a favorite, and for this I am using Core Data.

I'd like to be able to re-use开发者_高级运维 a bunch of views for displaying the products, which means the stores object and the downloaded object would have to be the same kind.

Now, how would I go about best implementing the objects? Can I make a class such as this:

FavoriteProduct : NSManageObject // implementation

and then subclass

Product : FavoriteProduct // implementation

?

The CD class just doesn't give me everything. What would be the best way to merge these two object classes so I have as little work ahead of me in terms of implementing the different views for each object? Basically, I just want to be able to call the same methods, etc. on the Product objects as I would on the ones that are FavoriteProduct objects, and re-use views for both kinds. There's only a bit of difference between the two (one is of course stored as a favorite and has some extra values such as notes, tags, while the Product one doesn't).

Thanks in advance


I had the same question a while ago. Quick answer: you can't instantiate an NSManagedObject subclass without a context, so using an NSManagedObject as a super class for something that's not gonna be saved (since it's just viewed from the net), is probably not a great idea.

So for your case:

  • FavoriteProduct has to be a subclass of NSManagedObject
  • Therefore Product (super class of FavoriteProduct) has to be a subclass of NSManagedObject context too
  • But then it has to be created with a context, not good

As a workaround you can have a "fake"/temporary context for objects of type Product but not FavoriteProduct and do the hierarchy the way you described (which seems a bit hacky to me)

One other possible solution is to have this hierarchy:

  • Product : NSObject (or whatever)
  • FavoriteProduct : Product
  • StoredProduct : NSManagedObject

It this case, implement all your methods on Product/FavoriteProduct as usually, and have bindings from FavoriteProduct to StoredProduct (ie. you can have a property "storedProduct" on your FavoriteProduct that will be used to update CoreData whenever some of the properties on FavoriteProduct are changed)

I'd be interested to see what others do in these kind of situations

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜