开发者

How do I change an NSManagedObject's type?

开发者 https://www.devze.com 2023-01-20 16:43 出处:网络
Let\'s say I have an inheritance hierarchy as follows: Device <- Ethernet开发者_如何学JAVADevice <- WirelessDevice

Let's say I have an inheritance hierarchy as follows:

Device <- Ethernet开发者_如何学JAVADevice <- WirelessDevice

So a Wireless device is a subclass of EthernetDevice, which is a subclass of Device.

Ok, so if a user creates a Device object and the user later decides that it's actually a Wireless device, how do I change the object's type? At the moment I'm creating a new WirelessDevice managed object and essentially moving through each property of the Device object and assigning it to the same property of the WirelessDevice object. Then telling the ManagedObjectContext to delete the Device object. Is this the easiest way? Is there a form of typecasting or a copy style method that also notifies the ManagedObjectContext of the change?

Thanks


First off, with Core Data, you generally want to avoid inheritance. If you want to be able to conveniently switch from an EthernetDevice to a WirelessDevice, I would just have on Device entity with a "type" property with a value from an enum similar to this:

typedef enum _DeviceTypes{
   EthernetDeviceType,
   WirelessDeviceType
}

That way changing from one type to another is a simpler matter of changing that one value. How different are the methods in your EthernetDevice class vs your WirelessDevice class? If they're drastically different, then creating a new entity and deleting the old one might actually be the easiest way (tons of switch(){} blocks all over your code can take away from readability and such).

0

精彩评论

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