Iphone 我是否可以创建自定义托管对象类的新实例而不必经过NSEntityDescription?
从一个苹果的例子中,我有这样一个:Iphone 我是否可以创建自定义托管对象类的新实例而不必经过NSEntityDescription?,iphone,cocoa,cocoa-touch,core-data,macos,Iphone,Cocoa,Cocoa Touch,Core Data,Macos,从一个苹果的例子中,我有这样一个: Event *event = (Event*)[NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:self.managedObjectContext]; 事件继承自NSManagedObject。有没有办法避免这种对NSEntityDescription的奇怪调用,而直接调用alloc+init类?我需要
Event *event = (Event*)[NSEntityDescription
insertNewObjectForEntityForName:@"Event"
inManagedObjectContext:self.managedObjectContext];
事件
继承自NSManagedObject
。有没有办法避免这种对NSEntityDescription的奇怪调用,而直接调用alloc+init
类?我需要写我自己的初始化器来完成上面的事情吗?或者,NSManagedObject
是否已经足够智能,可以这样做?NSManagedObject
提供了一个名为。您可以使用它来执行更传统的alloc
/init
对。请记住,此返回的对象不是自动删除的。要使其正常工作,有很多事情要做-insertNewObject:。。。这是迄今为止最简单的方法,不管是否怪异。说:
托管对象与其他对象不同
对象的三种主要方式—托管
对象存在于一个环境中
由其托管对象上下文定义
... 因此,有很多工作要做
创建新的托管对象的步骤
并将其适当地纳入
核心数据基础架构。。。你是
不愿意凌驾
initWithEntity:insertIntoManagedObjectContext:
也就是说,你仍然可以这样做(进一步阅读我链接的页面),但你的目标似乎“更容易”或“不那么奇怪”。我想说,你觉得奇怪的方法实际上是最简单、最正常的方法。我从Dave Mark和Jeff LeMarche的更多iPhone 3开发中找到了一个明确的答案 如果您使用
NSEntityDescrpiton
上的方法而不是NSManagedObjectContext
上的方法将新对象插入NSManagedObjectContext
,确实让您感到不安,那么您可以使用category将实例方法添加到NSManagedObjectContext
创建两个名为NSManagedObject Insert.h和NSManagedObject Insert.m的新文本文件
在NSManagedObject Insert.h中,放置以下代码:
import <Cocoa/Cocoa.h>
@interface NSManagedObjectContext (insert)
- (NSManagedObject *)insertNewEntityWithName:(NSString *)name;
@end
您可以在希望使用此新方法的任何位置导入NSManagedObject Insert.h。然后替换针对NSEntityDescription
的insert调用,如下所示:
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
使用更简短、更直观的:
[context insertNewEntityWithName:[entity name]];
分类不是很重要吗?我遇到了完全相同的问题。事实证明,您可以完全创建一个实体,而不是首先将其添加到存储中,然后对其进行一些检查,如果一切正常,则将其插入存储中。我在XML解析会话期间使用它,在该会话中,我只想在正确且完全解析实体之后插入实体 首先,您需要创建实体:
// This line creates the proper description using the managed context and entity name.
// Note that it uses the managed object context
NSEntityDescription *ent = [NSEntityDescription entityForName:@"Location" inManagedObjectContext:[self managedContext]];
// This line initialized the entity but does not insert it into the managed object context.
currentEntity = [[Location alloc] initWithEntity:ent insertIntoManagedObjectContext:nil];
然后,一旦您对处理感到满意,您只需将您的实体插入存储即可:
[self managedContext] insertObject:currentEntity
请注意,在这些示例中,已在头文件中定义currentEntity对象,如下所示:
id currentEntity
哦,是的,但是永远不要覆盖
initWithEntity:insertIntoManagedObjectContext:
awakeFromInsert
是进行初始化的适当位置。
id currentEntity