嘗試翻譯《More iPhone 3 Development Tackling iPhone SDK 3》中Core Data部分(未完待續...)

蔣曉冬發表於2011-08-23

enter image description here

正在研究iOS中Core Data框架,所以嘗試翻譯了一下MoreiPhoneDevelopment這本書中的CoreData部分,也算不上翻譯,只是按照自己學習的理解寫下來的,英文能力和技術水平有限,所以很多有紕漏的地方希望大家一起探討、學習。有時間我會持續更新,希望大家一起學習進步,另外祝賀圖靈新社群上線,讓我們有了一片可以交流的園地!

Core Data is a framework and set of tools that allow you to persist your application’s data to the iPhone’s file system automatically. Core Data is a form of something called object-relational mapping, or ORM, which is just a fancy way of saying that Core Data takes the data stored in your Objective-C objects and translates (or maps) that data into another form so that it can be easily stored in a database, such as SQLite, or into a flat file.

CoreData 是一個在iOS系統中自動的為你儲存應用程式相關資料的框架和一套工具。CoreData是物件-關係-對映或者叫做ORM的一種表現形式,以一種特別的方式把資料儲存在Objective-C物件中並把他們翻譯(對映)到另一種形式, 這樣就可以輕鬆的儲存到類似SQLite資料庫,或者是普通檔案中。

Core Data can seem like magic when you first start using it. Objects are simply dealt with as objects, and they seem to know how to save themselves into the database or file system. You won’t create SQL strings or make file management calls—ever. Core Data insulates you from some complex and difficult programming tasks, which is great for you. By using Core Data, you can develop applications with complex data models much, much faster than you could using straight SQLite, object archiving, or flat files.

當你第一次開始用CoreData框架時,會覺得它比較神奇。物件就是簡單的被當做物件處理,而且它們好像自己就知道如何將自己儲存到資料庫或者檔案中。你不用寫SQL語句或者是呼叫檔案管理器。CoreData使你不再糾結於複雜的程式碼,這對你非常的方便。使用CoreData框架你可以使用複雜的資料模型來開發應用程式,這比直接使用SQLite資料庫或者運用物件歸檔或者將資料儲存到檔案中要更加高效!

Technologies that hide complexity the way Core Data does can encourage “voodoo programming”—that most dangerous of programming practices where you include code in your application that you don’t necessarily understand. Sometimes, that mystery code arrives in the form of a project template. Or, perhaps, you downloaded a utilities library that did a task for you that you just don’t have the time or expertise to do for yourself. That voodoo code does what you need it to do, and you don’t have the time or inclination to step through it and figure it out, so it just sits there, working its magic … until it breaks. Though this is not always the case, as a general rule, if you find yourself with code in your own application that you don’t fully understand, it’s a sign you should go do a little research, or at least find a more experienced peer to help you get a handle on your mystery code.

一種最危險的程式設計實踐,是在你的應用程式中出現了一些你並不一定明白的程式碼。 有時候專案模板中會出現一些令人難以理解的神祕程式碼。你可能會下載一些工具庫來幫助你解決那些你沒有時間或者不懂的技術難題。因為你沒有時間或者沒有興趣一步步的除錯或者把程式碼弄明白,VOODOO Code就是你需要做的,因為程式碼就在那裡執行,直到它退出。雖然不是常常如此,但是一般來說,如果在你的應用程式中找到了一些你不是完全理解的程式碼,你就需要做一些工作,或者至少是找到有經驗的同事來幫助你解決那些神祕的程式碼。

The point is that Core Data is one of those complex technologies that can easily turn into a source of mystery code that will make its way into many of your projects. Although you don’t need to know exactly how Core Data accomplishes everything it does, you should invest some time and effort into understanding the overall Core Data architecture.

有一點值得注意的就是,CoreData是一種可以讓你在你的大多數專案中輕鬆使用的複雜技術。儘管你沒有必要去了解CoreData如何完成的,但是你也應該抽出點實踐和精力,並加以努力去了解CoreData框架的整體結構。

In this chapter, we’ll start with a brief history of Core Data, and then dive into the Core Data template itself. By dissecting Xcode’s default Core Data template, you’ll find it much easier to understand the more complex Core Data projects we get into in the following chapters.

在這章裡,我們將會簡短的介紹CoreData的歷史,並且將深入到CoreData專案模板中。通過剖析Xcode中預設的CoreData模板,你將會意識到CoreData專案很容易理解,讓我們進入這章。

A Brief History of Core Data

Core Data has been around for quite some time, but it just became available on the iPhone with the release of iPhone SDK 3.0. Core Data was originally introduced with Mac OS X 10.4 (Tiger), but some of the DNA in Core Data actually goes back about 15 years, to a NeXT framework called Enterprise Objects Framework (EOF), part of NeXT’s WebObjects web development tool set.

CoreData出現了很長一段時間了,但是直到iPhone SDK3.0釋出的時候才被融入iPhone中。雖然CoreData是在Mac OS X10.4(Tiger)的時候才出現的,但是其中的一部分是遺傳自15年前的NeXT公司一套NeXT's WebObjects web開發工具中的一個叫做Enterprise Objects Framework (EOF)的框架。

EOF was designed to work with remote databases, and it was a pretty revolutionary tool when it first came out. Although there are now many good ORM tools for almost every language, when WebObjects was in its infancy, most web applications were written to use handcrafted SQL or file system calls to persist their data. Back then, writing web applications was incredibly time- and labor-intensive. WebObjects, in part because of EOF, cut the development time needed to create complex web applications by an order of magnitude.

EOF是一套操作遠端資料庫的工具,當它第一次出現的時候被認為具有相當大的革命性。盡然現在每一種變成語言都擁有了屬於自己的ORM工具,但是在WebObjects初期,大多數網路應用程式都是靠著手寫SQL語句或者是檔案系統呼叫來儲存資料的。那時,編寫網路應用不僅需要大量的時間,而且還消耗著大量的勞力。WebObjects,部分原因是由於EOF,大量削減了編寫複雜的網路應用的開發時間。

In addition to being part of WebObjects, EOF was also used by NeXTSTEP, which was the predecessor to Cocoa. When Apple bought NeXT, the Apple developers used many of the concepts from EOF to develop a new persistence tool called Core Data. Core Data does for desktop applications what EOF had previously done for web applications: It dramatically increases developer productivity by removing the need to write file system code or interact with an embedded database.

除了作為WebObjects的一部分以外,EOF框架還被稱作NeXTSTEP,NeXTSTEP是Cocoa框架的前輩。在蘋果公司收購了NeXT以後,蘋果公司的開發工程師們運用了大量的EOF思想開發出一套新的持久層工具,叫做CoreData。CoreData框架用EOF以前為編寫網路應用的結果來開發桌面應用程式。這比直接寫入系統檔案或者操作嵌入式資料庫大大提高了開發人員的工作效率。

Let’s take a look at a Core Data Xcode template.

讓我們看看Xcode中CoreData的專案模板

Creating a Core Data Template Application

建立一個CoreData模板應用程式

Fire up Xcode and select New Project… from the File menu, or press ....N. When the new project assistant comes up, select Application under the iPhone OS heading in the left column, and then select Navigation-based Application from the upper-right pane. In the lower-right pane, make sure the box labeled Use Core Data for storage is checked, as in Figure 2–1. That check box is how we tell Xcode to give us all the code and extra stuff we need to start using Core Data. Not all Xcode project templates have this option, but it’s available for both the Navigation-based Application and Window-based Application templates.

啟動Xcode並在檔案選單中選擇New Project,或者cammand+N,當新建專案選項出現後,在左側導航欄選擇iPhone OS下的Application後,在右側的專案模板中選擇Navigation-based Application。在下方的視窗中確保Use Core Data for storage選擇框被選中,參考圖2-1. 勾選了Use Core Data for storage就是告訴Xcode為我們生成CoreData專案模板生成程式碼和額外的一些東西。並不是所有的Xcode專案模板都有這個選項,只是出現在the Navigation-based Application and Window-basedApplication 模板中。 enter image description here 圖2-1

Call your project CoreData. Now build and run the application. It will work fine in either the simulator or on a physical device. It should look something like Figure 2–2.

給新建的專案命名為CoreData。現在執行應用程式,它會在模擬器或者是物理裝置上良好執行。看上去會像圖2-2 enter image description here

If you press the plus icon in the upper-right corner, it will insert a new row into the table that shows the exact date and time the plus button was pressed. You can also use the Edit button to delete rows. Exciting, huh?

如果你按下右上角的+號鍵,會自動在表中建立附加著準確時間和日期資訊的行。你也可以用Edit鍵來刪除行。對嘛?

CAUTION: Early versions of the Core Data Navigation-based Application template had a small bug. If you deleted the last row, the application would crash. This was fixed in SDK 3.1.

注意:早期的Core Data Navigation-based Application模板存在著一個小bug,如果你刪除了最後一行,則應用程式會崩潰,這個問題在SDK3.1中得到解決。

Under the hood of this simple application, a lot is happening. Think about it—without adding a single class, or any code to persist data to a file or interact with a database,pressing the plus button created an object, it with data, and saved it to a SQLite database created for us automatically. There’s plenty of free functionality here.Now that you’ve seen an application in action, let’s take a look at what’s going on behind the scenes.

看似簡單的模板,卻實行了大量操作。試想一下,沒有建立一個類,甚至沒有寫下一行程式碼來使用檔案或者資料庫來儲存資料,按下+號鍵建立了一個含有資料的物件並且為我們自動儲存。這裡面有大量的方法,你已經看見了應用程式的執行,現在我們來看看內部是如何工作的。

Core Data Concepts and Terminology Like most complex technologies, Core Data has its own terminology that can be a bit intimidating to newcomers. Let’s break down the mystery and get our arms around Core Data’s nomenclature. Figure 2–3 shows a simplified, high-level diagram of the Core Data architecture. Don’t expect it all to make sense now, but as we look at different pieces, you might want to refer back to the diagram to cement your understanding of how they fit together.

和其他複雜的技術一樣,CoreData也有令初學者畏懼的專業術語。讓我們打破這種神奇,來了解一下這些術語。 圖2-3顯示了CoreData框架的基本結構。不要期望現在能把所有的相關知識都弄明白,我們將會逐一的學習,在以後的學習過程中,你可能需要回顧這幅插圖來鞏固你對CoreData各個部分如何組合在一起工作的理解。 enter image description here

There are five key concepts to focus on here. As you proceed through this chapter, make sure you understand each of the following: .. Persistent store .. Data model .. Persistent store coordinator .. Managed object and managed object context .. Fetch request Once again, don’t let the names throw you. Follow along, and you’ll see how all these pieces fit together.

這裡有五個關鍵概念,通過本章,確保你能理解每一項。 ..儲存倉庫 ..資料模型 ..儲存倉庫協調器 ..管理物件和管理物件上下文 ..提取請求 再一次,不要被這些名字所迷惑,隨著逐步的深入學習,你將會了解到這些部分是如何組合在一起協調工作的。

The Data Model and Persistent Store The persistent store, which is sometimes referred to as a backing store, is where Core Data stores its data. By default on the iPhone, Core Data will use a SQLite database contained in your application’s documents folder as its persistent store. But this can be changed without impacting any of the other code you write by tweaking a single line of code. We’ll show you the actual line of code to change in a few moments.

儲存倉庫有時又被稱為後背儲存器,它是CoreData框架用來儲存資料的。在iPhone的預設情況下,CoreData會使用被包含在你的應用程式資料夾中的SQLite資料庫作為資料儲存倉庫。但是,這是可以改變的,而且不會影響任何其他程式碼。 一會兒將向你展示具體的程式碼。

CAUTION: Do not change the type of persistent store once you have posted your application to the App Store. If you must change it for any reason, you will need to write code to migrate data from the old persistent store to the new one, or else your users will lose all of their data— something that will likely make them quite unhappy.

注意:不要在你向AppStore提交了你的應用程式以後,改變儲存倉庫的型別。如果你有理由一定需要改變的話,你需要編寫程式碼進行資料遷移,不然的話,你應用程式的使用者將會丟失所有資料,這會令他們非常不高興!

Every persistent store is associated with a single data model, which defines the types of data that the persistent store can store. If you expand the Resources folder in the Groups & Files pane in Xcode, you’ll see a file called CoreData.xcdatamodel. That file is the default data model for your project. The project template we chose gave us a single persistent store and an associated data model. Single-click CoreData.xcdatamodel now to bring up Xcode’s data model editor. Your editing pane in Xcode should now look like Figure 2–4. As you design your own applications, this is where you’ll build your application’s data model.

每一個儲存倉庫都和一個獨立的資料模型聯絡在一起,該模型定義了可被儲存在儲存倉庫中的資料型別。如果你開啟Xcode左側選單欄中的Groups & Files下的Resources folder資料夾,會看見一個名為CoreData.xcdatamodel的檔案。 這個檔案是你專案的預設資料模型。我們選擇的專案模板提供了一個儲存倉庫和一個相關聯的資料模型。點選CoreData.xcdatamodel檔案可以進入資料模型編輯器。現在你在Xcode中的編輯視窗應該類似於圖2-4.如果你設計自己的應用程式,這也是你建立你自己的資料模型的地方。

In this chapter, we’ll explore the data model that comes with the template. In Chapter 3,we’ll actually use the editor to create a custom data model.

在這一章節中,我們會結合著模板來探索一下資料模型。在第三章,我們將會建立自定義的資料模型。

Take a look at the data model editor. Notice the single rounded rectangle in the middle of the editing window. That rectangle is known as an entity. In effect, an entity is like a class definition, wrapping your various data elements under a single umbrella. This particular entity has the name Event, and it features sections for Attributes and Relationships. There’s a single attribute, named timeStamp, and no relationships.

看一下資料模型編輯器,注意編輯器視窗中間的獨立圓角長方形。這個圓角長方形被認為是實體,事實上,一個實體就是一個類的定義,將各種資料元素包含起來。這個特別的實體被命名為Event,它包含屬性和關係兩種特性。這裡有只有一個屬性,被稱為timeStamp,並且沒有關係特性。

Click off the entity rectangle. The title bar should turn a light pink. Click back on the entity, and it will turn blue, indicating the entity is selected.

點選實體的圓角長方形,標題欄會變成粉色,回點實體,標題欄會變為藍色,標題實體被選中。

The entity was created as part of this template. If you use this template to create your own Core Data application, you get the Event entity for free. As you design your own data models, you’ll most likely delete the Event entity and create your own entities from scratch.

這個實體是作為模板的一部分被建立的。如果你應用這個模板來建立你自己的CoreData應用程式,這個Event實體將會自動被建立。如果你設計自己的資料模型,大多數情況下會刪除這個Event實體,而重新建立自己的實體。

enter image description here

TheDataModelClass:NSManagedObjectModel Although you won’t typically access your application’s data model directly, you should be aware of the fact that there is an Objective-C class that represents the data model in memory. This class is called NSManagedObjectModel, and the template automatically creates an instance of NSManagedObjectModel based on the data model file in your project. Let’s take a look at the code that creates it now.

儘管你不會直接訪問你的應用程式中的資料模型,但是你也應該知道有一個Objective-C類代表著記憶體中的資料模型。這個類是NSManagedObjectModel,並且模板會根據你專案中的資料模型來自動建立一個NSManagedObjectModel類的實力。現在讓我們看一下已經建立的程式碼。

In your project window’s Groups & Files pane, open the Classes group and single-clickCoreDataAppDelegate.m. At the top of the editor pane, click the function menu to bring up a list of the methods in this class (see Figure 2–5). Select -managedObjectModel,which will take you to the method that creates the object model based on the CoreData.xcdatamodel file.

在你的專案中的左側window’s & Files視窗,開啟Classes group並且點選CoreDataAppDelegate.m,在編輯視窗頂部,點選方法選單,會出現這個類中的方法列表(圖2-5)。選擇-managedObjectModel,將會展示根據CoreData.xcdatamodel檔案所建立的物件模型的方法。

enter image description here

方法應該是這樣: /** Returns the managed object model for the application. If the model doesn't already exist, it is created by merging all of the models found in the application bundle. */

  • (NSManagedObjectModel *)managedObjectModel {

    if (managedObjectModel != nil)

    {

    return managedObjectModel;

    }

    managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];

    return managedObjectModel;

}

The first thing it does is check the instance variable managedObjectModel to see if it’s nil. This accessor method uses a form of lazy loading. The underlying instance variable doesn’t actually get instantiated until the first time the accessor method is called. For this reason, you should never, ever access managedObjectModel directly (except within the accessor method itself, of course). Always make sure to use the accessor methods. Otherwise, you could end up trying to make calls on an object that hasn’t been created yet.

第一件事就是需要堅持例項變數managedObjectModel是否為nil。這種訪問採用了懶載入的一種方式。直到訪問器第一次被呼叫,底層的例項變數才會被例項化。 因此,你永遠不要直接訪問managedObjectModel(當然除了訪問器本身)。確保總是使用訪問器方法。否則,你最終可能會試圖使用一個尚未建立物件。

TIP: The data model class is called NSManagedObjectModel because, as you’ll see a little later in the chapter, instances of data in Core Data are called managed objects.

資料模型類之所以被稱為NSManagedObjectModel,就像本章稍後你將會看到的,在CoreData中資料例項被稱為managed objects

If managedObjectModel is nil, we’ll go get our data models. Remember how we said that a persistent store was associated with a single data model? Well, that’s true, but it doesn’t tell the whole story. You can combine multiple .xcdatamodel files into a single instance of NSManagedObjectModel, creating a single data model that combines all the entities from multiple files. This line of code takes any .xcdatamodel files that might be in your Xcode project and combines them together into a single instance of NSManagedObjectModel: managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];

如果managedObjectModel為nil,我們就需要建立我們自己的資料模型。還記得我們如何描述的一個儲存倉庫關聯與一個資料模型的?對,就是這樣,不過,它並沒有說明全部問題。你可以將多個xcdatamodel檔案組合成一個NSManagedObjectModel類的例項,可以聯合多個檔案的實體中來建立一個資料模型。這行程式碼需要專案中的xcdatamodel檔案聯合組成一個NSManagedObjectModel的例項:managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];

相關文章