I am using Core Data to save some strings. I have the following class called Results
Results.h
#import <CoreData/CoreData.h>
@interface Results : NSManagedObject
@property(nonatomic, retain) NSString *lessondate;
@property(nonatomic, retain) NSString *lesson;
@property(nonatomic, retain) NSString *location;
@property(nonatomic, retain) NSString *start;
@property(nonatomic, retain) NSString *end;
@end
Results.m
#import "Results.h"
@implementation Results
@dynamic lessondate;
@dynamic lesson;
@dynamic location;
@dynamic start;
@dynamic end;
@end
The following is my code to perform the save:
-(void)saveLesson{
Results *result = (Results *)[NSEntityDescription insertNewObjectForEntityForName:@"Diary" inManagedObjectContext:managedObjectContext];
result.lessondate = calendarDateString;
result.lesson = [NSString stringWithFormat:@"%@", lessonText.text];
result.location = [NSString stringWithFormat:@"%@", locationTest.text];
result.start = [NSString stringWithFormat:@"%@", startTimeText.text];
result.end = [NSString stringWithFormat:@"%@", endTimeText.text];
NSError *error;
// here's where the actual save happens, and if it doesn't we print something out to the console
if (![managedObjectContext save:&error])
{
NSLog(@"Problem saving: %@", [error localizedDescription]);
}
[self dismissViewControllerAnimated:YES completion:nil];
}
But when I try to save the data in the app, the app crashed and shows these errors
2013-02-18 11:46:25.705 After managedObjectContext: <NSManagedObjectContext: 0x1f892480>
2013-02-18 11:46:33.762 -[NSManagedObject setLesson:]: unrecognized selector sent to instance 0x1f80b380
2013-02-18 11:46:33.764 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSManagedObject setLesson:]: unrecognized selector sent to instance 0x1f80b380'
Can someone please tell me why this is crashing? The exact same code is in another app and that works fine.
You are creating an entity different from what you expect.
You are calling
which creates entity
Diary. Put@"Results"as a first argument for the method.While you are assigning the created
Diaryentity into aResultsobject, it is only a syntactic sugar—the real object underneath is what you have passed as an entity name.Diaryobject doesn’t have thelessonproperty, and you get the exception.