I try to extend NSManagedObject. Using XCode I created MyBox.m and MyBox.h (directly from the xcdatamodel file).
Then I modified these files:
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface MyBox : NSManagedObject
@property (nonatomic, retain) NSDate * endDate;
@property (nonatomic, retain) NSNumber * globalId;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSDate * startDate;
-(NSString *)sayHello;
@end
and
#import "MyBox.h"
@implementation MyBox
@dynamic endDate;
@dynamic globalId;
@dynamic name;
@dynamic startDate;
-(NSString *)sayHello {
return @"hello";
}
@end
I can fetch all myBoxes
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"MyBox" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSMutableArray *myBoxes = [context executeFetchRequest:fetchRequest error:&error];
but later I call
MyBox *myBox = [myBoxes objectAtIndex:indexPath.row];
[myBox sayHello];
it compiles but then I get
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSManagedObject sayHello]: unrecognized selector sent to instance 0x8e73fc0'
If I only read a value like
NSLog(@"%@", myBox.name);
it works
I found similar problems here, but no solution. Thanks for your help.
For Swift 5.0
This issue is present when you create the CoreData object in this way:
let object = CoreDataClass()
print(object.someProperty) // this is emit crash
I've just got the same issue. Solved it by changing class name to the name of my NSManagedObject subclass in myApp.xcdatamodeld -> configurations -> default -> entities -> myEntity
.
Assuming you have set the class name correctly on the MyBox
entity, I would guess that the app has an older version of your Core Data managed object model. Clean your build and delete the app on the simulator/device for good measure. To be 100% sure, also delete your derived data folder.
If it doesn't work after that, I'll bet that you haven't set the entity class name correctly. Print out your NSEntityDescription
and make sure it is what you expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With