我正在使用Core Data来保存一些字符串。我有以下类名为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
以下是执行保存的代码:
-(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];
}
但是当我尝试在应用中保存数据时,应用程序崩溃并显示这些错误
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'
有人可以告诉我为什么会崩溃吗?完全相同的代码在另一个应用程序中,并且工作正常。
答案 0 :(得分:5)
您正在创建一个与您期望的实体不同的实体。
您正在致电
[NSEntityDescription insertNewObjectForEntityForName:@"Diary"
inManagedObjectContext:managedObjectContext];
创建实体Diary
。将@"Results"
作为方法的第一个参数。
当您将创建的Diary
实体分配到Results
对象时,它只是一个语法糖 - 下面的真实对象是您作为实体名称传递的内容。
Diary
对象没有lesson
属性,并且您获得了异常。