2
votes

I have a Core Data class, ZSShotCD, generated from xcdatamodeld (and yes, I've set the class correctly in the model). I don't want to put any custom methods in there because I might need to regenerate at some time, so I've subclassed it as ZSShot. Here are some relevant bits:

First, the generated class:

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@interface ZSShotCD : NSManagedObject

@property (nonatomic, retain) NSString * shotDescription;
@property (nonatomic, retain) NSString * shotType;

@end

The .m file is what you'd expect, with a bunch of @dynamic declarations for the properties. I haven't messed with it at all.

Now for the subclass - ZSShot.h:

#import <Foundation/Foundation.h>
#import "ZSShotCD.h"

@interface ZSShot : ZSShotCD
- (NSString *)MainText;
@end

And the .m file:

#import "ZSShot.h"

@implementation ZSShot

- (NSString *)MainText
{
    NSString *mainText = [NSString stringWithFormat:@"%@ %@", [self valueForKey:@"shotType"], [self valueForKey:@"shotDescription"]];
    return mainText;
}

When I try to call the MainText method on an instance of ZSShot, like this:

cell.shotDescriptionLabel.text = [item MainText];

I get:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ZSShotCD MainText]: unrecognized selector sent to instance 0x8d130c0'

That instance (cell) has no problem with attributes defined in the entity, (it's pulling data from Core Data just fine) and I'm using code that is basically identical to that used elsewhere on classes built on other entities - the only difference being my attempt to use a method defined in the subclass.

Can anyone shed some light on this?

1
what is the type of item ? check it with NSLog(@"%@", [item class]), I think it should be ZSShotCD. BTW why not use category instead of subclass. - KudoCC
Can you please show the code where you create item? As @KudoCC said, it seems like it is a ZSShotCD, not a ZSShot - which is confirmed by the exception you are getting. - Paulw11
I'll bet you obtained your "instance of ZSShot" by doing a core-data fetch, in which case it wasn't an instance of ZSShot at all, but an instance of ZSShotCD. The error message is pretty clear about this. @KudoCC's suggestion of a category is spot-on, then you don't have to cast or fiddle or do anything with your fetch result to make it an instance of the subclass. - RobP
You were all exactly right. I'm new to this so hadn't understood how sub-classing works (or doesn't) in an NSManagedObject environment. I've now reworked my subclass as a category and it's working. Thanks guys. - Dick Kennedy

1 Answers

4
votes

You need to set the class for the entities in your xxx.xcdatamodeld, like this: enter image description here

(UserInfo is the subclass of UserBase which is a NSManagedObject class.)

Or you will get a instance for the base class which don't have the method you call.