Delve into Manage memory Essentials learning(2)

Object Creation and Storage 

1In Objective-C, like any other object-oriented programming language, the object acts like a data package with predefined(預先確定的) behaviors 

oc中,像其他面向對象的編程語言,這個對象就像擁有前面定義的行爲的數據包。

2、Cocoa (for OS X) and Cocoa Touch (iOS) already provide a library containing an extensive list of(一個廣泛的列表) objects for you to use as they are or create your own objects based on them—we call it code reuse.(代碼複用)

55 未看好

3、In object-oriented programming approaches, an object is an instance of a class. The class will determine the behavior of the object, the messages (methods) it receives, and sometimes who has access to send these messages in order to obtain a response. 

在面向對象編程方法中,一個對象是一個類的實例,這個類將決定對象的行爲、它收到的消息........

4、A class describes the properties and behaviors of a specified object, just like the blueprint of a house will describe the properties of the house, such as the number of doors in the house. Similarly, for a number, an instance of a class named NSNumber, its class provides many ways to obtain, analyze, compare, and convert the object's internal numeric value. 

一個類描述了一個指定對象的屬性和行爲,就像一個房子的計劃將會描繪房子的屬性,例如門的數量,類似的,對於一個數字對象,類NSNumber實例,它的類提供很多方式來獲取、解析、比較、轉換那個對象的內部的數字值。

5、Creating a cell with [tableView:dequeueReusableCellWith Identifier:@"anyReusableIdentifier" forIndexPath:indexPath] sets an identifier to the cell in order to reuse it with other content when it's no longer visible on the screen.(創建這個標識,是爲了,當這個cell不在屏幕中的時候,這個cell能被重用)

 For example, if there is a table view with 15 elements, and in your iOS device, there are 12 cells visible in the screen, when you scroll up to see the other 3 elements, there will still be 12 cells visible. In this case, using reuse identifiers, instead of creating 15 UITableViewCells, it will create at least 13 different cells (11 fully visible cells and 2 partially visible cells), and when a cell disappears from the screen (scroll up), it is reused to load the newest visible element, appearing at the bottom. (當一個cell 不見得時候,它被重用來加載最新的可視的元素,出現在底部)(邏輯流程是怎樣的呢,首先是創建,桌面上的所有的都是新創建,雖然標誌符都一樣,但是桌面的都是不同的新的cell,以後複用怎麼複用呢,通過這個標識符去找,發現有沒有在用的cell,就拿出來複用)

6NSArray *secondSampleArray = nil;

secondSampleArray = @[@"Item 1", @"Item 2"];

You can see that we set secondSampleArray to nil, and in Objective-C, nil means that secondSampleArray has no value or an address(驗證過,沒值也沒地址,打印爲NULL,根本沒有規模,所以也說上去改變規模). It is only later that we insert the two NSStrings "Item 1" and "Item 2" into secondSampleArray to make the size of the array 2. 

你能看到nil,oc中,nil意味着secondSampleArray沒值或沒一個地址,到了後面我們插入兩個元素進入數組後,才讓數組的範圍爲2.

7Immutability also brings performance benefits when used in things such as strings and dictionaries as mutability will bring some overhead(開銷) due to the need to allocate and deallocate chunks of memory when the string or dictionary is modified.

8In the case of NSArray and NSMutableArray, NSMutableArray is not thread-safe and can present weird(奇怪的) bugs if you use multithreading. So, generally, try to use NSArray as the de facto(事實上的) array to use unless you really need NSMutableArray. [NSMutableArray是線程不安全的,多線程中會出現各種奇怪的問題,除非你真正需要NSMutaleArray,不然就用NSArray]

9、The allocation and initialization methods will allocate a chunk of memory to hold the object's content and set an empty value to it, until you assign a value yourself. 

The empty value differs depending on the object's type: Boolean (BOOL) objects receive the value NO, integers (int) receive 0, oat numbers ( oat) receive 0.0, and the rest of the objects receive nil. 

[這個規則很有趣]

10、It's possible to first allocate memory for your object, and later in the code, initialize it, but it's not recommended at all. (還可以這樣啊)

11which(init method) will return a nil value 

The singleton pattern 

1Design patterns are solutions, mostly reusable code solutions, to solve and prevent common issues. It makes a developer's life easier. 【設計模式阻止相同的問題出現】

2、However, singletons can be misused as global variables, which makes for bad programming practice(單例不能誤做全局變量). 

3Singletons are also implemented using static methods, which is not good for unit testing as they cannot be mocked(模仿) or stubbed(徹底根除). So, only use a singleton in the correct context and not in every situation that you encounter. (不是所有地方用上單例,要考慮環境和上下文)

4、An example already implemented by Apple in the UIScreen class is the mainScreen method. mainScreen獲得一個單例

5When you first call the method, the instance is not created yet. It will then be initialized and returned as expected; however, from the second time the method is called, it doesn't create a new instance but returns the existing one. 

6There are two ways to store data in objects, they are properties and instance variables (兩種方式儲存值)The latter should be used just for objects and values exclusively(唯一的,排外的) handled by the class itself, not from outside. Properties, on the other hand, for objects and values are accessible from outside (by other classes). (後者只能在自己的類使用,屬性可以被外部使用)

7If they are declared in the header file as part of the @interface block, 

they have public scope and if declared in the implementation le as part of the @ implementation block, they have private scope. Generally, they should be private: 

   @implementation Book {

     int _numberOfPages;

     int _numberOfChapters;

     NSArray *_authorsInfo;

} 

頭文件裏面的有公共範圍,在implementation裏面沒有範圍。

8、To easily understand your code, instance variable starts with an underscore(下劃線); it doesn't affect the way they work, but it's a convention highly recommended to be followed. 

實例變量加下劃線是慣例,建議遵循。

Managing Your Application Data 

1We will also cover some common pitfalls(陷阱) and assumptions(假定) that people commonly associate with the development of iOS applications. One example will be image loading, where if the developers are not careful in planning the proper architecture of their application(不注意應用結構), they will encounter situations where the application will lag or run out of(用完) memory and lead to an application crash. 

2As with all computing devices, iPads and iPhones have a finite(有限的) amount of memory and you may be tempted(有興趣的) to(短語:會) develop applications without any concern about the memory usage. Doing so is not ideal for development as memory optimizing and management should always be at the top of your mind when doing any type of development, regardless of whatever platform you will be developing on. (內存優化和管理應該時刻記在心裏,不管什麼開發平臺)

3、Now, the amount of memory does look impressive(印象深刻的) as you fondly remember the days of old(當你深情地回憶過去的日子), where your old desktop ran on 256 MB of RAM, but do remember that iOS does not let you play with the full 512 MB or 1 GB RAM. The OS will allocate some to system processes in your device, and you will only get a subset of the available RAM for your application. (app不能佔用全集內存,只能佔用子集內存)

4In your application, everything will occupy memory and storage space(內存和存取空間). Some of the biggest culprits(罪魁禍首) are binary assets(二進制), such as videos and images, which can be total resource hogs(貪婪的人) to even your class objects that can take up precious space if you do not take note of them when doing your development. So, let's start with image optimization as almost every application will make use of images in one way or another. 

5Any application will look boring and drab(單調的) without the usage of .png and some nice images. However, one thing about images is that they take up much more memory than their file size implies. A single 1 MB .png le can occupy double or triple their memory size when loaded into the memory. The reason is because PNG is basically a compressed le format, such as a ZIP file. So, all the image data is compressed into a PNG file and when your application needs to display your PNG image. It needs 

to load the PNG file into memory, uncompress it, and then it will be able to get the image data to be used by your code and will consume more memory in the process. So, if your application has 20 MB of PNG files, you are easily looking at 40 MB or more of RAM allocation just for images 

6Save your image as PNG-8 instead of PNG-24 as PNG-8 consumes less RAM than their equivalent(相等的) PNG-24. Only use PNG-24 if you need the alpha channel for transparency(透明). The difference between PNG-8 and PNG-24 is the image quality and the number of colors that you can have. The 8 and 24 means 8-bits per pixel and 24-bits per pixel respectively(各自的). So, PNG-8 can only support up to 256 colors while PNG-24 can support up to 16 million colors, so PNG-24 is the best option if you need to display images with a lot of colors such as photographs(照片), while logos and user interface elements such as icons can probably get by with PNG-8. PNG-24 also supports alpha transparency, which is good for images that need to have a transparent background. So, knowing which format to use in which situation will help you in reducing the memory consumption of your application.
7If you can use JPG files, then use them as they are a lossy format(有損格式), and it means that you will get a bit of image degradation(退化降級), but generally the image degradation is almost invisible to the naked eye. However, note that JPG files do not support alpha transparency.
8PNG is a lossless format, which means that there is no image degradation when you use PNG files, but it comes at a price that it consumes more RAM when loaded into your device compared to a JPG, which is a lossy format.So, keep PNG les and JPG les to an absolute minimum if you can and only use them if you have to.
9
lazy loading

There is also one more advantage(還有一個優勢), that is, it minimizes(降低) the start up time of your application since you only load the resources on demand and this takes less time to load.So,yougain a speed boost in terms of time. (降低你的應用啓動時間,需要少的時間來加載,速度改進)

10、This is one of the simplest implementations where we just override the getter method of a class 

- (A_CLASS*)aObject {

     if (aObject == nil){

         aObject =[ [A_CLASS allco] ]init];

    }

}

You can put the preceding(在前的) code in place of the normal getter method of your class. 

11Also, tasks such as loading images and getting data from a remote server are considered as slow processes and will slow down your application. 

12I am sure that you have used iOS apps where when you scroll down a UITableView view object you will see a noticeable lag(顯而易見的卡頓) as new images are loaded into the newly revealed cells. (新的cell被加載到新的出現的cell)

13In this world, where people are used to images loading quickly on their desktop and mobile phones, such slowness and laggy(遲緩的) UI are not acceptable and can mean the difference between a user staying engaged with your application or uninstalling your application(UI的流暢度直接影響到用戶是否直接用你的應用還是卸載你的應用).

14The fundamental mantra(基本的口頭禪) is that you must not let your users wait for 1 second or even 1 millisecond more than what is absolutely necessary. One tip to compensate(補償) for the perceived(感知) slowness of an application is to have a simple animation such as fading in an image(淡入一個圖像) after showing a spinner(顯示一個轉輪) in order to give the user the perception(觀念) that the application is not actually very slow since there is an animation playing 

15Reusing your controls is a must if you are experiencing huge memory usage, which is impacting the usability(合用,可用性) of your iOS application . Later on, we will cover how to use the tool called Instrument in Xcode to monitor the memory usage. Creating objects is an expensive process and has a performance cost(創建對象是花費的程序,有性能花費).

16Reusing UITableViewCell is a lot faster and will enhance the performance of your application. Luckily, Apple has already created code for us to reuse a cell, which can be implemented easily with a few lines of code (重用cell是更快,將會提高你的性能)

17Looking at the preceding code, you can see that we attempt to assign a cell using the dequeueReusableCellWithIdentifier method, then it will return a pointer to that cell if it already exists. Next, our code (!cell) will check whether that pointer is not nil, then it will create the cell. This is the exact same technique we used in the previous section Lazy loading, except that we apply this technique to an iOS control, which in this case, is a UITableViewCell object. These few lines of code serve three functions: (UitableViewCell的創建用到了懶加載)

(1)This helps to prevent a situation where your app is lagging when you are scrolling up as it eliminates(排除) the need to create new instances of UITableViewCell. (減緩遲鈍)

(2)If you have 1,000 rows of data and only 4 rows are visible on screen at any given time, then it makes no sense(沒必要) to create 1,000 UITableViewCell when you only need to create five(只需要創建五個). A few other cells can be partially visible and hence(因此) need to be created too. So, the five cells will only be created as it needs to be visible to the user while the remaining cells are not loaded. 

(3)While a single UITableViewCell class occupies a lot of memory, storing 1,000 of them is not easy, and through a few extra lines of code, you can avoid unnecessary memory usage and use the memory you save for other parts of your code 

Caching

1Caching is a concept where you store resources on disk(磁盤) or memory for faster access(緩存爲快速接近). Caching will occupy more space, but in situations where you need to worry more about loading speed than memory, caching can be a very good technique to use(當你當心加載速度,緩存是一個好的方法).下面三種要考慮:

(1)Downloading a large file such as an image or even a movie 

(2) Write the file to a disk

(3) Read the files from the disk and display them 

2If you follow the normal method as mentioned earlier, a bottleneck(瓶頸) that you will face is slow loading of the file from disk. Disk access can be as slow as 10,000 or even 1,000,000 slower than memory access(硬盤讀取是內存讀取的上萬甚至上百萬的慢) and it won't make a good user experience as the user will be kept waiting while your app is loading the files from disk. Caching will help slow this problem as your file is saved to memory where read access is faster. (從內存中加載更快)

3This is good from a user point of (從用戶角度)view as they do not need to wait a long time for
the file to be loaded and can help to optimize the user experience of your application since every second wasted can lead to the user moving away from your application. Caching on disk or memory has its pros and cons (
有點和缺點)as illustrated in the following table: 

                            Disk                                                                                  Memory

Storage         Persistent,as data is not lost when device is                Ephemeral , as data is lost when 

                      Switched off(關閉)                                                            device is switched off

Speed           Slow                                                                                    Fast

Storage Size Large                                                                                   Small,as memory is generally lesser than

                                                                                                                   disk storage

4So as a rule of thumb(這是經驗之談), it will be best to do all caching on memory first and then move to caching on disk only when your application is running low on memory or you experience memory warning errors. If you are downloading large files such as movies, you will need to store the movie file on disk since the file normally will not be able to fit into memory.

5As a sidenote(旁註), caching uses a few algorithms for implementation, such as Most Recently Used (MRU) or Least Recently Used (LRU). MRU means the cache will discard the most recently used items first when the cache is full, while LRU is the reverse opposite(相對反面的) where the least recently used items will be discarded instead. The implementation strategy is out of the scope of this book and it is up to the manufacturer(製造商) to decide. 

6Fortunately, we do not need to write a lot of code to implement ef cient caching. There are a few iOS caching libraries that we can use and they are available for us to use. So, in this section, we will look at one of the most popular caching libraries. (有一些庫能幫我們做這些事)

Object seriallization

1Serialization is the method or concept where we convert data structures or objects into a format for it to be stored in memory or disk for storage, or to be transmitted across a network link. 

2It(serialization序列化) can also assist in(幫助) memory management as it provides an alternative mechanism(另一種機制) where we save some files to disk instead of memory, which is usually the case for big files, such as movie files. Serialization formats include JSON, XML, YAML(序列化格式包括json,xml,yaml), and so on. 

3And luckily for iOS developers, Apple provides us with a robust(強健的) framework that helps us take away the low- level code when we want to do serialization. So, when we want to store our data structures or objects in memory or disk, we can use Apple's frameworks such as Core Data or NSCoding, which provides an abstraction(抽象的) layer and hides away the lower-level coding for us. 

4When it comes to data saving or serialization, we tend to stick with(堅持) the one method that we are most familiar with. However, this is not a good way of doing things as various methods have their pros and cons(有點和缺點), and we should consider our use case before we decide on the best method. To this extent(在這個程度上), Apple has provided us with a few different methods for data serialization and it is up to us, the developers, to decide which method suits us best. One of the simplest ways is to use NSCoding. What is NSCoding? NSCoding is basically a protocol provided by Apple for you to encode and decode your data into a buffer(進入到一個緩衝區), which can then be persisted to disk for persistent storage. (方法不能固定,要選擇最佳的方法)

5Usage of the NSCoding protocol also involves the NSKeyedArchiver and NSKeyedUnarchiver methods as NSCoding is a protocol with delegate methods for serializing our data structure and custom object into a format that can be stored in memory or disk. NSKeyedArchiver and NSKeyedUnarchiver are the methods that will actually do the work of storing our serialized data into disk for persistent storage. So to kick things off, we will use an example to help us understand how serializing and archiving works for iOS applications. 

6Usage of the NSCoding protocol also involves the NSKeyedArchiver and NSKeyedUnarchiver methods as NSCoding is a protocol with delegate methods for serializing our data structure and custom object into a format that can be stored in memory or disk. NSKeyedArchiver and NSKeyedUnarchiver are the methods that will actually do the work of storing our serialized data into disk for persistent storage. So to kick things off, we will use an example to help us understand how serializing and archiving works for iOS applications. 

7There is no need to call initWithCoder and encodeWithCoder anywhere in our code as those method calls are called when you call unarchiveObjectWithFile and archiveRootObject. However, you need to implement initWithCoder and encodeWithCoder as these two methods need to contain the necessary code to encode and decode the isReset, userName, and score variables that form OurCustomObject. As you can see, NSCoding is a relatively powerful way to store data to disk compared to NSUserDefaults(nscoding 是一個跟nsuerdefaults比較相對有力量的方式), and the code is quite easy to understand and write. However, if you need more power features for data storage, NSCoding will not be the best choice and Core Data will be the better option as it has more features such as being able to perform queries(諮詢), being optimized for speed(能別優化速度), support for different serialization formats(支持不能的系列化格式) such as XML, SQLite, or NSDate, among other benefits.

(CoreData很強大,比coding更強大)

8SQLite, for those familiar with Relational DataBase Management System (RDBMS), is a database based on the relational model. A SQLiteis, a RDBMS that is available for us in iOS, has a lot of the features and functions of RDBMS that many people are familiar with, such as ACID(增刪改查) properties, queries(諮詢), and so on. Core Data is Apple's framework for data storage and you can use Core Data to store data into a SQLite database. However, there are some cases when you need to use SQLite instead of Core Data. So, I will elaborate(精析) further on this 

(1) SQLite as a database is available on multiple platforms besides iOS. So this means that if you are developing an application that runs on multiple platforms or has the possibility to run on other non-iOS platforms, SQLite will be the option for you to seriously consider since you will avoid framework lock-in using Core Data. SQLite also is faster than NSCoding, plus it adds querying functionality, which is not possible if you use NSUserDefaults (多個平臺使用的話,用數據庫)

(2) Also, if you have experience with SQLite and your use case for data storage is very straightforward along with no experience with Core Data, then you should choose SQLite. 

(3) It does not require a Model-View-Controller (MVC) conceptual model. (它沒有強制需要yigmv概念模型)

9Now, this does not mean that SQLite should be the default data storage solution for you when you need to store data to disk. This is because there are other options such as Core Data and various other factors such as speed and ease of coding, which will play a big part in your decision-making as we will see later in this chapter and the chapter on Core Data later on

SQLite versus Core Data

1Core Data is a rich and sophisticated(豐富和複雜的) object graph management framework with a lot of bells and whistles(鈴鐺和口哨) that you require for complex use cases 

2Apple mentions that the Core Data framework provides generalized(廣義的) and automated(自動的) solutions to common tasks associated with object life cycle and object graph management, including persistence, which means it prevents you from writing a lot of code to do your everyday data storage tasks. 

3Core Data uses models that are your objects and these are the model in the commonly used MVC architecture. These enable you to store whole objects and it ties in very closely with the controller and view classes of your iOS application. So, developers who are using MVC architectures will have no problem absorbing(吸收) the Core Data concepts and models. 

4The tools for development using the Core Data framework is tied in deeply into Xcode and it enables developers to quickly write code and lay out their data models in a fast and ef efficient manner, and thus, save you time, which allows you to spend it on other parts of the project. 

5Core Data framework is also available for the Mac OS, and this enables reusability of your code if you intend to create a Mac version of your application. (Mac也能用)

6With Apple's iCloud storage and computing platform, you can use Core Data to take advantage of iCloud to sync your application and user data across multiple devices such as iPads and so on. iOS 8 has tighter integration with(緊密聯繫) iCloud with the introduction of the CloudKit framework, which has new functionality such as allowing partial download of datasets(數據集) and all this is only possible using Core Data. ()

7SQLite is a pure RDBMS and many people confuse Core Data with SQLite. SQLite is a RDBMS, pure and simple. So, it has a lot of the features that you will associate with RDBMSes, such as ACID properties, queries, and so on. However, that is where it ends. Core Data is an abstraction(抽象) layer on top of a data store, which can be SQLite or other forms of data persistence, such as XML files. So, using Core Data will still enable you to store data in SQLite, but there will be some occasions when you prefer to use SQLite over Core Data 

(Core Data mvc特性,以及存儲多樣性,既可以用數據庫存儲,也可以用XML存取)

8If data portability(可移植性) is an important feature for you, then using SQLite should be your preferred choice as SQLite is platform-independent, while Core Data is for Apple platforms only(SQLite可以移植不同平臺,但是core data只能用在Apple). So, if you use SQLite, you can be assured that your data files can be moved and accessed on almost any platform that supports SQLite, not only Apple- supported platforms. 

9Core Data ultimately is an abstraction layer between your code and the database. 

10However, sometimes you want to get down to(認真考慮) the lower levels of your code and avoid abstraction layers to understand how the code works. So, using SQLite will allow you to do that, as it allows you to do low level optimization if you are working with large datasets(數據集). Core Data can also be used to abstract the Sqlite access to save on development time and make your code cleaner.

11、Ultimately, there are no hard and fast rules on when and where to use Core Data or SQLite. On every engineering project, there are questions and decisions to be made, which encompass factors such as amount of resources and platform scalability(可拓展性) since Core Data only supports Apple platforms and if you intend to support non-Apple platforms. Core Data might not be a good choice. So, using the Core Data framework allows you to have a rapid solution for simple applications, but it also ties you into Apple's framework, which impedes(妨礙) data portability(可移植性) as if you create an application where a user's data such as game data needs to be present on another non-Apple device. You will encounter a technical lock-in(技術鎖定) if you use Core Data. 

12In summary, this chapter covered the management of your application data with regards to(關於) caching data to memory and data storage on to disk. We also covered the pros and cons of using the various storage frameworks for various situations and did a few code examples on using the NSCoding protocol and the SDWebImage open source caching framework. 

CoreData 

1If you do any serious form of iOS development, data persistence is something that you are bound to come across sooner rather than later(短語,宜早不宜遲的). After all, what good is an app when it does not save your user data and requires you to fill it in again when you start the app again subsequently(隨後的)? (你需要保存數據和強制再次填充,這是一個好的app?)

2This is where data persistence comes into the scene(進入現場). As it is, iOS developers have a few options(幾個選型) for data persistence ranging from property list, binary format to SQLite, and so on. (屬性list 到二進制格式再到數據庫)

3、The first thing you need to know is that Core Data is not another method of data persistence per se(本身); it is actually an abstraction over SQLite, plists, and so on(Core Data是SQLite ,plists文件的抽象). This means that you can actually use Apple's Core Data API to save your data into the persistent store just by using the Core Data API without needing to write plist-specific or SQLite-specific code if you choose to store your data as plists or SQLite respectively. This abstraction layer illustrates the basic concept of why Core Data is so powerful. 

4Now that you have your mind blown, the abstraction layer means that you can just use the Core Data APIs, and the abstraction layer will handle all the storage-specific code for you as all this high-level stuff will help you get away from writing low-level stuff, specific for each different data persistent format such as SQLite, property list, and so on. 

5Core Data integrates very tightly with iCloud and provides a host of(一大堆)benefits related to iCloud, such as data synching(數據同步). It also allows you to do entity modeling(做實體建模) with the benefits of querying(諮詢的) while making it very fast in terms of access speed plus giving you the freedom to choose the storage type that can be SQLite, XML, or NSDate(還能選擇數據的類型). With all the benefits that Core Data provides, it comes with a trade-off(附帶了一個權衡) in which  you need to write a bit more code compared to NSCoding. However, as we will see later, the amount of code is not a lot, and the Core Data framework is not complex to understand too. (雖然碼比NSCoding多,但是還是不多,代碼比較好理解)

6、A few more things that I would like to mention about Core Data is that since it is so tightly integrated into the Apple platforms, you can have access to a lot of related classes such as NSFetchedResultsController that make it easy for you to get your entities into UITableViews. It also has a nice graphical object model editor(好的圖形對象模型編輯器) that allows you to easily think about your object/entity design and conceptualize it easily using Core Data's visual tools. With all these benefits, let's dig into(深入研究 == delve into) Core Data now. 

7store types 

(1)NSSQLiteStoreType: This is the option you most commonly use as it just stores your database in a SQLite database. 

(2)NSXMLStoreType: This will store your data in an XML file, which is slower, but you can open the XML file and it will be human readable. This has the option of helping you debug errors relating to storage of data. However, do note that this storage type is only available for Mac OS X. (注意,這種方式不能再mac上使用)

(3)NSBinaryStoreType: This occupies the least amount of space and also produces the fastest speed as it stores all data as a binary file, but the entire database binary need to be able to fit into memory in order to work properly. 

(4)NSInMemoryStoreType: This stores all data in memory and provides the fastest access speed. However, the size of your database to be saved cannot exceed the available free space in memory since the data is stored in memory. However, do note that memory storage is ephemeral(臨時地) and is not stored permanently to disk(沒有持久化給硬盤).

8、concepts :(Entity and Attributes)

Now, these terms may be foreign to you. However, for those of you who have knowledge of databases, you will know it as tables and columns. So, to put it in an easy-to-understand picture, think of Core Data entities as your database tables and Core Data attributes as your database columns. (將實體想象爲數據庫tables,Core Data 屬性想象爲數據庫裏面的列)

9So, Core Data handles data persistence using the concepts of entity and attributes, which are abstract data types, and actually saves the data into plists, SQLite databases, or even XML files (applicable only to the Mac OS). Going back a bit in time, Core Data is a descendant(子孫) of Apple's Enterprise Objects Framework (EOF), which was introduced by NeXT, Inc in 1994, and EOF is an Object-relational mapper(映射器) (ORM), but Core Data itself is not an ORM. Core Data is a framework for managing the object graph, and one of its powerful capabilities is that it allows you to work with extremely large datasets(能管理極端大的數據集合) and object instances (對象實例) that normally would not t into memory by putting objects in and out of memory when necessary. Core Data will map(映射) the Objective-C data type to the related data types, such as string, date, and integer, which will be represented by NSString, NSDate, and NSNumber respectively(分別得). So, as you can see, Core Data is not a radically(從根本) new concept that you need to learn as it is grounded in(短語:建立在) the simple database concepts that we all know. Since entity and attributes are abstract data types, you cannot access them directly as they do not exist in physical terms. So to access them, you need to use the Core Data classes and methods provided by Apple. 

10common used classes:

(1)NSManagedObject           Accessing attributes and rows of data    (2)NSManagedObjectContext        ——> Fetching data and saving data 

(3)NSManagedObjectModel       Storage                                                                 (4)NSFetchRequest    >Requesting data 

(5)NSPersistentStoreCoordinator      —— Persisting data                                       (6)NSPredicate   Data query 

(1)NSManagedObject: This is a record that you will use and perform operations on and all entities will extend this class.

(2)NSManagedObjectContext: This can be thought of as an intelligent scratchpad(便條簿) where temporary copies are brought into it after you fetch objects from the persistent store. So, any modi cations done in this intelligent scratchpad are not saved until you save those changes into the persistent store, NSManagedObjectModel. Think of this as a collection of entities or a  database schema(一個數據庫模式), if you will.  

(3)NSFetchRequest: This is an operation that describes the search criteria(條件、標準), which you will use to retrieve(檢索) data from the persistent store, a kind of the common SQL query that most developers are familiar with. 

(4) NSPersistentStoreCoordinator(協調者): This is like the glue(膠帶) that associates your managed object context and persistent. Without this, your modifications will not be saved to the persistent store. (沒有這個的話,你的修改將不會保存在持久的倉庫)

(5)NSPredicate(謂詞): This is used to define logical conditions used in a search or for filtering in-memory. Basically, it means that NSPredicate is used to specify how data is to be fetched or filtered and you can use it together with NSFetchRequest as NSFetchRequest has a predicate property (用來過濾的)

Putting it into Practice

1Do note that all attribute names must be in lowercase and should not have spaces in them. For example, we will use Core Data to store customer details mentioned earlier as well as retrieve, update, and delete the customer records using the Core Data framework and methods. (屬性必須是小寫,並且在他們中間沒有空格)

2、Note that memory management is still a real issue in the post-ARC world. So what we have done is follow best practices that will help us avoid memory leaks. (在arc世界,內存管理仍然是一個問題)

3、So, to wrap it all up, Core Data is not something that is overly(極度) complex and the code to use Core Data is pretty straightforward as we have seen in our code examples shown earlier. The Core Data framework is a relatively easy framework to use to handle data storage abstraction without worrying about different data storage formats(不要擔心不同的數據格式). 

4So, 保存數據the steps we need to remember are: 

  1. Get the instance of NSManagedObjectContext, which sets
    persistentStoreCoordinator using managedObjectModel.
  2. Create an instance of NSManagedObject and set the values you want to save. 
  3. Use an object of the NSManagedObjectContext type and call the save method since the context will represent all changes that you have done and you need to call the save method in order to save the changes from the context to disk.

5The concepts that you have to know are the Core Data classes such as NSManagedObject, NSManagedObjectContext, NSPersistentStoreCoordinator, and so on and the related methods such as save and deleteObject. With these simple lines of code, you can leverage(利用) the power of the Core Data framework to do data persistence on a high-level abstraction without concerning yourself with the low-level data format specifications. In the next chapter, we will be introduced to key-value programming and how it can be used to allow us to be notified of state changes. So, I hope you enjoyed this chapter on Core Data!

CoreData中間有幾段沒有細看

Key-value Programming Approaches

1Key-value coding is a really cool function that works well with key-value observing. It allows you to code less and create very elegant(優美的) solutions and code modules. There are many cases in a real application when something changes and another part of the application should be affected. (實際應用中有一部分動了,另一部分應該受到影響)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章