H档案:
@interface TaskTypeEntity : NSManagedObject
@property (nonatomic, retain) UIColor *color;
@property (nonatomic, retain) UIImage *image;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSNumber * status;
@property (nonatomic, retain) NSSet *task;
@property (nonatomic, retain) NSSet *taskCount;
@end
M档案:
@implementation TaskTypeEntity
@dynamic color;
@dynamic image;
@dynamic name;
@dynamic status;
@dynamic task;
@dynamic taskCount;
- (void) add:(TaskTypeEntity*)data
{
TaskTypeEntity *taskTypeEntity = [NSEntityDescription insertNewObjectForEntityForName:ENTITY_NAME inManagedObjectContext:content];
taskTypeEntity.name = data.name;
taskTypeEntity.image = data.image;
taskTypeEntity.color = data.color;
BOOL result = [content save:nil];
if (result) {
NSLog(@"success%@", data);
}else{
NSLog(@"fail");
}
}
@end
设置属性时,它不起作用:
TaskTypeEntity *taskTypeEntity = [TaskTypeEntity alloc];
taskTypeEntity.name = @"dfdfd";
[taskTypeModel add:taskTypeEntity];
错误: * 由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:' - [TaskTypeEntity setName:]:无法识别的选择器发送到实例0x8a7b070'
请帮帮我,谢谢
答案 0 :(得分:0)
根据NSManagedObject
类引用:
重要说明:此方法是指定的初始化程序 NSManagedObject。您不能简单地初始化托管对象 发送它。
以上引用文字中的参考方法为insertNewObjectForEntityForName:inManagedObjectContext:
,因此可以使用:
NSManagedObject *object = [NSEntityDescription
insertNewObjectForEntityForName:@"Item"
inManagedObjectContext:context];
编辑(作为回应......)
这段代码完全错误:
TaskTypeEntity *taskTypeEntity = [TaskTypeEntity alloc];
即使TaskTypeEntity
不是NSManagedObject
,它仍然是错误的,因为您从未调用过初始化程序。
它是NSManagedObject
的事实使它更加错误,因为你永远不应该分配/初始化其中一个。
为什么不尝试这样的事情(我假设您使用的是图像和颜色的可变形属性):
+ (instancetype)taskTypeEntityInMOC:(NSManagedObjectContext*)context
name:(NSString*)name
image:(UIImage*)image
color:(UIColor*)color
{
TaskTypeEntity *taskTypeEntity = [NSEntityDescription insertNewObjectForEntityForName:ENTITY_NAME inManagedObjectContext:content];
taskTypeEntity.name = name;
taskTypeEntity.image = image;
taskTypeEntity.color = color;
return taskTypeEntity;
}
然后你可以称之为......
TaskTypeEntity *taskTypeEntity =
[TaskTypeEntity taskTypeEntityInMOC:context
name:(NSString*)name
image:(UIImage*)image
color:(UIColor*)color];