I have a method that takes as a string the name of an entity in my sqlite database that I am trying to streamline to use as little repeating code as possible.
here I have entity as id that I am trying to set to the require object type in readiness to make the call to insert a row.
problem is when I make the call to NSEntityDescription entity is still of class id
id entity;
if ([entityName isEqualToString:@"yadda yadda"]) {
entity = [EntityYadda class];
}
else if ([entityName isEqualToString:@"blah blah"]) {
entity = [EntityBlah class];
}
else if ([entityName isEqualToString:@"Foobar"]) {
entity = [EntityFoobar class];
}
for (int x=0; x<[data count]; x++) {
entity = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:context];
Where am I going wrong?
Thanks
I have 7 different entities all with identical fields so I am trying to dynamically assign the required entity class to 'entity' so in my loop I will have only one line using NSEntityDescription an property settings.
Well, you've already had the thought of "why not one entity with a flag field denoting type?", and that is an excellent question, and I would very much recommend going with that route.
If, for some reason, you cannot, you could declare the identical fields in a protocol, and then declare that these 7 entities all conform to the same protocol. In your method, your type declaration would be (instead of id
): NSManagedObject<MyCustomProtocol> *
.