Cocoa Core Data新手教程 [英] Cocoa Core Data newbie how-tos

查看:159
本文介绍了Cocoa Core Data新手教程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个伟大的未开发的大众的.NET开发人员渴望尝试他们的手在Mac OS X开发之一。目前我正在弄清楚Cocoa的各种元素,并且对核心数据有点困扰。



我注意到了Web上的大部分文档和资源涉及一个广泛的端到端教程,从模型开始,生成类,基于文档的UI等。没有足够的似乎集中在每一个位,或至少没有足够的例子。



有人可以指点我在正确的方向,是在线材料还是书,可以给我详细的指导各种位?也许我陷入了.NET世界,但我仍然认为在数据访问层等。我想知道CRUD的基础,在设置持久存储,创建一个实体,编辑,保存存储等。只是基础,没有详细说明UI。如果我可以单元测试各种位,也会很好。



我想我试图进入正确的心态 - 任何.NET开发知道适合的阅读材料,像我们这样的人看可可编程?



非常感谢,
Dany。



为了安静你的好奇心,我会在CRUD的答案刺,虽然它不会是你想要的答案。答案是,没有Core Data的CRUD模式,至少不是你的想法。原因是Core Data不是数据访问层。它是一个对象图管理框架。这意味着Core Data的显式的,预期的作业是管理对象实例的图。此图具有约束(例如关系的基数或单个实例属性的约束)以及用于通过图形级联更改(例如删除)的规则。核心数据管理这些约束。因为对象图可能太大而无法存储在内存中,Core Data为您的对象图提供了一个接口,通过故障模拟[1]内存中的整个对象图(对象实例在首次引入受管对象上下文,并且被触发以便懒惰地从持久存储中填充它们的属性)和唯一化(在上下文中仅创建特定实体实例(在持久存储中)的一个内存中实例)。



核心数据只是发生使用磁盘持久性存储来实现大对象图的接口。在SQLite持久存储的情况下,这种实现只是发生使用SQL兼容的数据库。这是一个实现细节,但是。例如,您可以创建一个内存持久存储,它不会将任何内容保存到磁盘,但允许Core Data照常管理对象图。因此,核心数据实际上不是数据访问层。以这些术语来思考它将会错过它的真实力量,并将导致沮丧。您不能将Core Data与任意数据库模式一起使用(这就是为什么所有Core Data教程都从创建NSManagedObjectModel开始的原因)。您不应将Core Data用作持久性框架,并使用单独的模型层;您应该使用Core Data作为模型层,并利用Core Data为您将模型对象图形持久化到磁盘的能力。

这说,创建一个 NSManagedObjectContext (它提供了我上面描述的对象图接口):

  NSManagedObjectModel * mom = [NSManagedObjectModel mergedModelFromBundles:[NSArray arrayWithObject:[NSBundle mainBundle]]]; //虽然你可以创建一个模型(即在代码中)
NSPersistentStoreCoordinator * psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];

NSError * err;

//添加内存存储。至少需要一个持久存储
if([psc addPersistentStoreWithType:NSInMemoryPersistentStore configuration:nil URL:nil options:nil error:& err] == nil){
NSLog(@%@呃);
}

NSManagedObjectContext * moc = [[NSManagedObjectContext alloc] init];
[moc setPersistentStoreCoordinator:psc];

(注意,我假设你使用的是垃圾回收;



要添加实体实例(从上面连接 moc ):

  NSEntityDescription * entity = [NSEntityDescription entityForName:@MyEntityinManagedObjectContext:moc]; 
//如果MyEntity在moc.persistentStoreCoordinator.managedObjectModel中不存在,则实体将为nil NSManagedObject * obj = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:moc];

请注意,您需要实体描述才能创建托管对象



要更新实体实例:

  [obj setValue:myValue forKey:@attributeKey]; //或者在`obj`上使用任何更新状态的方法
NSError * err;
if(![moc save:& err]){
NSLog(@%@,err); //在保存中发生错误,可能是由于乐观锁定失败
}

实体实例:

  [moc deleteObject:obj]; 
if(![moc save:& err]){
NSLog(@%@,err); //在保存中发生错误,可能是由于乐观锁定失败
}

]:对于二进制或XML持久存储,整个图存储在存储器中


I am one of the great unwashed masses of .NET developers keen to try their hands at Mac OS X development. At the moment I am trying to figure out the various elements of Cocoa and getting a bit stuck on Core Data.

I noticed most of the documentation and resources available on the Web involve a broad end-to-end tutorial, beginning from models, generating classes, Document-based UI, etc. Not enough seem to be focused on each bit, or at least not enough examples.

Can someone please point me in the right direction, be it online material or books, that can give me detailed instruction of various bits? Maybe I'm stuck in the .NET world but I still think in terms of data access layer, etc. I'd like to know the basics of "CRUD", in setting up a persistent store, creating an entity, editing, saving to store, etc. Just the basics, without elaborating on the UI. It'd also be nice if I can unit test the various bits.

I guess I am trying to get into the correct mindset here - do any .NET devs out there know of appropriate reading material for people like us looking at Cocoa programming?

Many thanks, Dany.

解决方案

First, as Apple's documentation (and recurring comments from Apple engineers) state, Core Data is an "advanced" Cocoa technology. Grokking Core Data requires knowledge of a lot of Cocoa paradigms and patterns. Seriously, learn Cocoa first. Then write a project (or several) without Core Data. Then learn Core Data. Seriously.

To quiet your curiosity, I'll take a stab at the CRUD answer, though it's not going to be the answer you want. The answer is that there is no CRUD pattern for Core Data, at least not the way you think of it. The reason is that Core Data is not a data access layer. It is an object graph management framework. That means the explicit, intended job of Core Data is to manage a graph of object instances. This graph has constraints (such as cardinality of relationships or constraints on individual instance attributes) and rules for cascading changes (such as a delete) through the graph. Core Data manages these constraints. Because an object graph may be too large to be stored in memory, Core Data provides an interface to your object graph that simulates[1] an entire object graph in memory via faulting (object instances are not "faults" when first brought into a managed object context and are "fired" to populate their attributes from the persistent store lazily) and uniquing (only one in-memory instance of a particular entity instance (in the persistent store) is created in the context).

Core Data just happens to use an on-disk persistent store to implement the interface of a large object graph. In the case of an SQLite persistent store, this implementation just happens to use a SQL-compatible database. This is an implementation detail, however. You can, for example create an in-memory persistent store that does not persist anything to disk but allows Core Data to manage your object graph as usual. Thus, Core Data is not really a data access layer. To think of it in these terms will miss it's true power and will lead to frustration. You can't use Core Data with an arbitrary data base schema (this is why all Core Data tutorials start with creating the NSManagedObjectModel). You shouldn't use Core Data as a persistence framework and use a separate model layer; you should use Core Data as a model layer and take advantage of Core Data's ability to persist the model's object graph to disk for you.

That said, to create an NSManagedObjectContext (which provides the object graph interface I described above):

NSManagedObjectModel *mom = [NSManagedObjectModel mergedModelFromBundles:[NSArray arrayWithObject:[NSBundle mainBundle]]]; // though you can create a model on the fly (i.e. in code)
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:mom];

NSError *err;

// add an in-memory store. At least one persistent store is required
if([psc addPersistentStoreWithType:NSInMemoryPersistentStore configuration:nil URL:nil options:nil error:&err] == nil) {
  NSLog(@"%@",err);
}

NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init];
[moc setPersistentStoreCoordinator:psc];

(note that I'm assuming you're using Garbage Collection; this code leaks in a manual memory management environment).

To add an entity instance (continuting with moc from above):

NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:moc];  
//entity will be nil if MyEntity doesn't exist in moc.persistentStoreCoordinator.managedObjectModel

NSManagedObject *obj = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:moc];

Notice that you need an entity description to create a managed object (why tutorials start with the model) and that you can't create a managed object without a managed object context.

To update an entity instance:

[obj setValue:myValue forKey:@"attributeKey"]; //or use any method on `obj` that updates its state
NSError *err;
if(![moc save:&err]) {
  NSLog(@"%@", err); // an erro occurred in saving, perhaps due to optimistic locking failure
}

To delete an entity instance:

[moc deleteObject:obj];
if(![moc save:&err]) {
  NSLog(@"%@", err); // an erro occurred in saving, perhaps due to optimistic locking failure
}

[1]: For binary or XML persistent stores, the entire graph is stored in memory

这篇关于Cocoa Core Data新手教程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆