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. (实际应用中有一部分动了,另一部分应该受到影响)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值