I have a situation where I’ve created an NSArray of NSManagedObjects that are all derived from CoreData entities. The problem is that there are multiple entities in this array, but each of the entities in the array have a “name” property that I would like to retrieve.
I come from a C++ background, and if I were facing this problem I would make another class with properties I’d like to use and have all the child objects inherit from NSManagedObject and that class with the property I like. Unfortunately, I can’t see a way to do that with Objective C, as it doesn’t support multiple inheritance and I can’t figure out the paradigm to deal with little OOP problems like this. 🙁
—Background—
The use case scenario for what I’m dealing with is that I would like to fill a UITableView with cells from various characters from various object types. All the characters have a name, but they are all unique object types. Right now I can do one type just fine like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CharNameCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
CharacterWizard *wizards = (CharacterWizard*)[self.characters objectAtIndex:indexPath.row];
cell.textLabel.text = wizards.name;
return cell;
}
But, as you can see, this breaks down when I have different types. I”m sure there’s a more elegant solution to deal with this problem, but previous experience with other languages is getting in my way here (I think). Hope this wasn’t too long of a question.
One approach would be to define a
Characterclass, and makeCharacterWizardand other, similar classes into subclasses ofCharacter:Another approach would be to use a protocol, and have all of your NSManagedObjects implement the protocol. For instance, your protocol could be:
…then your
CharacterWizardclass would declare that it implements (and would proceed to implement)HasName:…and then your code can reference a generic object that implements the
HasNameprotocol (and can invoke the protocol’s methods) without knowing the actual class of the object:I’d probably recommend the
Characteroption if your other classes areCharacterFighter,CharacterRogue, and so on. If thenameproperty is the only thing your classes have in common, then the protocol would make more sense.