Cocoa Core Data 新手指南

发布于 2024-08-10 07:45:22 字数 419 浏览 2 评论 0原文

我是众多热衷于尝试 Mac OS X 开发的未经洗礼的 .NET 开发人员之一。目前我正在尝试弄清楚 Cocoa 的各种元素,但在核心数据上有点卡住了。

我注意到 Web 上提供的大多数文档和资源都涉及广泛的端到端教程,从模型、生成类、基于文档的 UI 等开始。似乎没有足够多的关注每一点,或者至少没有足够的例子了。

有人可以为我指出正确的方向,无论是在线材料还是书籍,可以为我提供各个方面的详细说明吗?也许我陷入了.NET世界,但我仍然在数据访问层等方面思考。我想了解“CRUD”的基础知识,例如设置持久存储、创建实体、编辑、保存存储等。只是基础知识,不详细说明 UI。如果我可以对各个部分进行单元测试,那就太好了。

我想我在这里试图进入正确的心态 - 任何 .NET 开发人员都知道适合像我们这样研究 Cocoa 编程的人的阅读材料吗?

非常感谢, 丹妮.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

如何视而不见 2024-08-17 07:45:22

首先,正如 Apple 文档(以及 Apple 工程师反复评论)所述,Core Data 是一项“高级”Cocoa 技术。 Grokking Core Data 需要了解许多 Cocoa 范式和模式。说真的,先学习Cocoa。然后编写一个(或多个)没有 Core Data 的项目。然后学习核心数据。严重地。

为了平息你的好奇心,我将尝试一下 CRUD 答案,尽管这不会是你想要的答案。答案是 Core Data 没有 CRUD 模式,至少不是你想象的那样。原因是 Core Data 不是数据访问层。它是一个对象图管理框架。这意味着 Core Data 的明确预期工作是管理对象实例图。该图具有约束(例如关系的基数或对单个实例属性的约束)和通过该图进行级联更改(例如删除)的规则。核心数据管理这些约束。由于对象图可能太大而无法存储在内存中,因此 Core Data 为对象图提供了一个接口,该接口通过故障模拟[1]内存中的整个对象图(当第一次将对象实例引入托管时,对象实例不是“故障”)对象上下文并被“激发”以延迟地从持久存储中填充其属性)和唯一(在上下文中仅创建特定实体实例(在持久存储中)的一个内存中实例)。

Core Data 只是碰巧使用磁盘上的持久存储来实现大型对象图的接口。对于 SQLite 持久存储,此实现恰好使用 SQL 兼容的数据库。然而,这是一个实现细节。例如,您可以创建一个内存中持久存储,它不会将任何内容保存到磁盘,但允许 Core Data 像往常一样管理您的对象图。因此,Core Data 并不是真正的数据访问层。从这些角度来思考它会错过它的真正力量并会导致挫败感。您不能将 Core Data 与任意数据库模式一起使用(这就是为什么所有 Core Data 教程都从创建 NSManagedObjectModel 开始)。您不应该使用 Core Data 作为持久性框架并使用单独的模型层;您应该使用 Core Data 作为模型层,并利用 Core Data 的能力将模型的对象图保存到磁盘。

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

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];

请注意,我假设您正在使用垃圾收集;此代码在手动内存管理环境中会泄漏) 。

要添加实体实例(继续上面的 moc):

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];

请注意,您需要实体描述来创建托管对象(为什么教程从模型开始)并且您如果没有托管对象上下文,则无法创建托管对象。

更新实体实例:

[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
}

删除实体实例:

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

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

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

裂开嘴轻声笑有多痛 2024-08-17 07:45:22

我会采取以下路线:

  1. 完成一般的 Apple Cocoa 教程:
    货币转换器
  2. 接下来,深入了解其 Cocoa Bindings 版本教程(如果您转向核心数据,绑定非常方便且非常重要)
  3. Cocoa Dev Central 的 “构建核心
    数据应用程序”
    教程

进一步阅读:
一如既往:Mac OS X 的 Cocoa 编程
一书
基于文档的应用程序架构 (ADC)
最后:一些之间的比较Cocoa 和 .net 方面

I would take the following route:

  1. Do the general Apple Cocoa tutorial:
    Currency Converter
  2. Next, dive into the Cocoa Bindings version of that tutorial (Bindings are very convenient and very important if you move on to Core Data)
  3. Cocoa Dev Central's "Build a Core
    Data App"
    tutorial

Further reading:
As always: the book Cocoa Programming for Mac OS X
Document-Based Application Architecture (ADC)
And finally: A comparison between some aspects of Cocoa and .net

尤怨 2024-08-17 07:45:22

核心数据实际上不是数据访问层(有关更多信息,请参阅我的其他答案)。但是如果您想要 Cocoa 的数据访问层怎么办?你有什么选择?我是一名专业的 Cocoa 和 Qt 开发人员,到目前为止,我已经设法避开 Windows 或 Java 企业世界,因此我对选项的评估可能与您的不完全匹配。来自企业生态系统,我希望您会发现这些选项有点可怕。我已经按照我预计对你来说最害怕到最不害怕的顺序订购了它们(大致上是可可味的,所以对我来说也大致是最熟悉到最不熟悉的)。找到列表中您的胃停止翻腾的位置,您就找到了解决方案...

  1. 虽然 Core Data 是一个非常强大的框架,用于管理 MVC 架构的模型组件的对象图,但您不是有义务使用它。您可以编写自己的模型层,并且仍然可以在 Cocoa MVC 世界中玩耍。这就是我们在 Core Data 之前所做的。如果需要,您仍然可以使用 Cocoa NSObjectControllerNSArrayControllerNSTreeController。因此,您可以使用数据库供应商的本机 C/C++ API 推出自己的数据访问层。

  2. BaseTen 框架是一个商业许可的类似 Core Data 的 API,位于 PostgreSQL 后端之上。它实际上更像是一个 ORM,而不是像 Core Data 这样的对象图管理框架,但 API 是相似的。我的理解是,它可以处理现有的(任意)模式或利用核心数据托管对象模型。它们提供了自己的 NSArrayController 子类,您可以将其用作 Cocoa 数组控制器的替代品。我个人从未使用过 BaseTen,所以我不能谈论它的实用性,但我听说过一些好东西。据我所知,它只是 PostgreSQL。

  3. Python-Objective-C 桥接器称为 PyObjC,非常成熟,自 10.5 起随 OS X 一起提供。使用这个桥,您可以用 Python 编写完整的 Cocoa 应用程序或编写混合 Python/Objective-C 应用程序。使用 PyObjC,您可以利用任何 Python ORM(例如 SQLAlchemy)来实现模型层。同样,这并不是没有工作,但对于一个有能力的 Python 和 Cocoa 程序员来说可能仍然相对容易。

  4. Apple 的企业对象框架(WebObjects 的一部分)现在是一个 Java ORM,其血统中还包含 Objective-C ORM。我相信,您仍然可以使用 WebObjects 编写桌面应用程序。我知道许多可可模式都延续了下来,但这是一个非常不同的野兽。我从未编写过 WebObjects 代码,因此我无法在这方面为您提供更多建议。

  5. 您可以使用跨平台工具包。 Qt 可以生成看起来不错的 Mac UI(尽管见下文)。 Qt 还有一个模型层框架,其中包括对 几个 数据库的 SQL 支持QtSql 模块。 Qt 根本不是 Cocoa。 Savy Mac 用户不喜欢非本机应用程序。 Qt 在 OS X 上的跨平台性能已经达到了最好的水平,但它并不完美。如果您可以保持本机,就这样做。

  6. 任何 Java Swing/SWT 废话。再说一次,这是一个很强大的东西,但它在 Mac 上看起来就像地狱,用户不喜欢它。

  7. OS X 上的 Mono 相对不成熟,我不知道 Mono 上的 .Net ORM 的状态如何。不过,这还是值得一看的。就 UI 而言,Mono-GTK 的东西在 OS X 上看起来相当糟糕。Qt 有一个名为 Qyoto 的 C# 绑定,它可以在 Mono 上运行。

Core Data really isn't a data access layer (see my other answer for more). But what if you want a data access layer for Cocoa? What are your options? I'm a professional Cocoa and Qt developer and so far I've managed to avoid the Windows or Java enterprise world, so my evaluation of the options may not match yours exactly. Coming from an enterprise-y ecosystem, I expect you'll find the options a little scary. I've ordered them in what I expect will be most to least scary for you (roughly most to least Cocoa-y and so also roughly most to least familiar for me). Find the spot on the list where your stomach stops lurching and you've found your solution...

  1. Although Core Data is a very powerful framework for managing the object graph of the model component of an MVC architecture, you're not obligated to use it. You can write your own model layer and still play in the Cocoa MVC world. This is how we did it before Core Data. You can still use the Cocoa NSObjectController, NSArrayController, and NSTreeController if you want. Thus, you can roll your own data access layer using the native C/C++ APIs of your data base vendor.

  2. The BaseTen framework is a commercial licensed Core Data-like API on top of a PostgreSQL backend. It is really more of an ORM than an object graph management framework like Core Data, but the API is similar. My understanding is that it can handle existing (arbitrary) schema or make use of Core Data managed object models. They provide their own NSArrayController subclass that you can use as a drop in replacement for Cocoa's array controller. I've never used BaseTen personally, so I can't speak to its utility, but I've heard good things. As far as I know it's PostgreSQL only.

  3. The Python-Objective-C bridge, called PyObjC, is quite mature and ships with OS X since 10.5. Using this bridge you can write complete Cocoa apps in Python or write a hybrid Python/Objective-C app. Using PyObjC, you could make use of any of the Python ORMs such as SQLAlchemy to implement your model layer. Again, not no work but perhaps still relatively easy for a competent Python and Cocoa programmer.

  4. Apple's Enterprise Object Framework, part of WebObjects, is now a Java ORM that has an Objective-C ORM in its lineage. You can, I believe, still write desktop apps using WebObjects. I understand that many Cocoa patterns carry over, but this is a very different beast. I've never written WebObjects code, so I can't give you much more advice on this one.

  5. You can make use of a cross-platform toolkit. Qt can produce decent looking Mac UIs (though see below). Qt also has a model-layer framework that includes SQL support for several data bases in the QtSql module. Qt is not Cocoa at all. Savy Mac users don't like non-native apps. Qt is about as good as it gets for cross-platform on OS X, but it's not perfect. If you can stay native, do it.

  6. Any Java Swing/SWT crap. Again, this is powerful stuff, but it looks like hell on the Mac and users don't like it.

  7. Mono on OS X is relatively immature and I don't know what the status of any of the .Net ORMs are on Mono. It's something to take a look at though. As far as UI, the Mono-GTK stuff looks pretty bad on OS X. There is a C# binding for Qt called Qyoto which runs on Mono.

偏爱自由 2024-08-17 07:45:22

看起来还没有人提到过这些书:

Doesn't look like anyone's mentioned these books yet:

  • Core Data by Marcus Zarra, The Pragmatic Programmers
  • Core Data for iPhone by Tim Isted, by Addison-Wesley (which, yes, is an iPhone book, but most of the principles of Core Data are shared across platforms)
鲸落 2024-08-17 07:45:22

不过,对于具体细节,您可能会找到 Apple 的 核心数据基础很有用 - 那里还有一个构建无 GUI 实用程序的教程。

For the nuts-and-bolts though, you might find Apple's Core Data Basics useful - there's also a tutorial for building a GUI-less utility there.

や莫失莫忘 2024-08-17 07:45:22

苹果销售电器和名人产品(好莱坞)
与企业发展完全无关
可可在完成之前就已经被放弃了,因为机会主义的可可触感
如果您正在寻找 delphi/vcl 或 .net 级别的任何内容,祝您好运(他们没有此类内容)

ps
这就是为什么苹果在服务器端和/或企业桌面端没有发言权,也就是说,他们不知道而且永远不会。也就是说,他们从事不同的业务。甚至他们的内部系统也是基于Linux的(只是为了让你知道!)

apple sells appliances and celebrity products (hollywood)
they have absolutely nothing to do with enterprise development
cocoa has been abandoned before even being finished for the opportunistic cocoa touch
if you are looking for anything at delphi/vcl or .net level, good luck to you (they have nothing of this kind)

ps
this is why apple has no saying on server side and/or enterprise desktop side, that is, they have no clue and they never will. that is, they're in a different business. even their internal systems are linux based (just to let you know!)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文