0

我正在使用 Core Data 来保存一些字符串。我有以下名为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

结果.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'

有人可以告诉我为什么会崩溃吗?完全相同的代码在另一个应用程序中并且运行良好。

4

1 回答 1

5

您正在创建一个与您期望不同的实体。

你在打电话

[NSEntityDescription insertNewObjectForEntityForName:@"Diary"
                              inManagedObjectContext:managedObjectContext];

创建实体Diary。作为@"Results"该方法的第一个参数。

当您将创建的Diary实体分配给一个Results对象时,它只是一个语法糖——下面的真实对象是您作为实体名称传递的对象。 Diaryobject 没有该lesson属性,您会得到异常。

于 2013-02-18T12:09:07.033 回答