Core Data by Tutorials 阅读笔记

最近一段时间都在找工作,对于 iOS 方面知识的学习有些懈怠,有什么好书麻烦推荐给我呀~


啾啾

Chapter 1

The NSPersistentContainer consists of a set of objects that facilitate saving and retrieving information from Core Data.

register(_:forCellReuseIdentifier:) guarantees your table view will
return a cell of the correct type when the Cell reuseIdentifier is provided to the dequeue method.

Core Data uses a SQLite database as the persistent store, so you can think of the Data Model as the database schema.

An entity is a class definition in Core Data. The classic example is an Employee ora Company. In a relational database, an entity corresponds to a table.

An attribute is a piece of information attached to a particular entity. For example, an Employee entity could have attributes for the employee’s name,position and salary. In a database, an attribute corresponds to a particular fieldin a table.

A relationship is a link between multiple entities. In Core Data, relationships between two entities are called to-one relationships, while those between one and many entities are called to-many relationships.

NSManagedObject doesn’t know about the name attribute you defined in your Data Model, so there’s no way of accessing it directly with a property. The only way Core Data provides to read the value is key-value coding, commonly referred to as KVC.

Like save(), fetch(_:) can also throw an error so you have to use it within a do block. If an error occurred during the fetch, you can inspect the error inside the catch block and respond appropriately.

Chapter 2 : NSManagedObject Subclasses

An attribute’s data type determines what kind of data you can store in it and how much space it will occupy on disk.

The number of bits reflects how much space an integer takes up on disk as well as how many values it can represent, or its range. Here are the ranges for the three types of integers:

Range for 16-bit integer: -32768 to 32767

Range for 32-bit integer: –2147483648 to 2147483647

Range for 64-bit integer: –9223372036854775808 to 9223372036854775807

When you enable Allows External Storage, Core Data heuristically decides on a per-value basis if it should save the data directly in the database or store a URI that points to a separate file.

You can save any data type to Core Data (even ones you define) using the Transformable type as long as your type conforms to the NSCoding protocol.

用一个 model 类替换用 kvc 的方式取值 : The best alternative to key-value coding is to create NSManagedObject subclasses for each entity in your data model.

context:

var managedContext: NSManagedObjectContext!
managedContext = appDelegate.persistentContainer.viewContext

增:

let entity = NSEntityDescription.entity(forEntityName: "Bowtie", in: managedContext)!
let bowtie = Bowtie(entity: entity, insertInto: managedContext)
//给 bowtie 赋值即可

查:

let selectedValue = "R"
let request = NSFetchRequest<Bowtie>(entityName: "Bowtie")
request.predicate = NSPredicate(format: "searchKey == %@", selectedValue!)
// 通过查找 entity bowtie 的属性之一 searchKey 来找到实体
do {
      let results = try managedContext.fetch(request)
      currentBowtie = results.first      
    } catch let error as NSError {
      print("Could not fetch \(error), \(error.userInfo)")
    }

改:

currentBowtie.rating = rating
try managedContext.save()

删:

managedContext.delete(currentBowtie)
try managedContext.save()

Chapter 3 : The Core Data Stack

The stack is made up for four Core Data classes:

  • NSManagedObjectModel 代表 model 文件,被管理的数据模型,可以添加实体及实体的属性,若新建的项目带CoreData,即为XXX.xcdatamodeld
  • NSPersistentStore 读写数据时选取的存储方法:
    • NSQLiteStoreType、NSXMLStoreType、NSBinaryStoreType、NSInMemoryStoreType
  • NSPersistentStoreCoordinator
    • bridge between the managed object model and the persistent store 数据库的连接器,设置数据存储的名字,位置,存储方式等
  • NSManagedObjectContext 操纵数据库实体时的工作板,所有操作必须调用其 save 方法才能在数据库上改变,负责应用与数据库之间的交互,增删改查基本操作都要用到
  • NSPersistentContainer 将四个部分包含起来
  • NSFetchRequest 获取数据时的请求
  • NSEntityDescription 描述实体

Chapter 4 : Intermediate Fetching

In case you didn't know, NSFetchRequest is a generic type. If youinspect NSFetchRequest's initializer, you'll notice it takes in type as a parameter<ResultType : NSFetchRequestResult>.

ResultType specifies the type of objects you expect as a result of the fetchrequest. For example, if you're expecting an array of Venue objects, the resultof the fetch request is now going to be [Venue] instead of [AnyObject]. This ishelpful because you don't have to cast down to [Venue] anymore.

NSFetchRequest has a property named resultType. Sofar, you’ve only used the default value, NSManagedObjectResultType. Here are all thepossible values for a fetch request’s resultType:

• .managedObjectResultType: Returns managed objects (default value).

• .countResultType: Returns the count of the objects matching the fetch request.

• .dictionaryResultType: This is a catch-all return type for returning the resultsof different calculations.

• .managedObjectIDResultType: Returns unique identifiers instead of full-fledged managed objects.

To create an NSAsynchronousFetchRequest you need two things : a regular

NSFetchRequest and a completion handler. Your fetched venues are contained in

NSAsynchronousFetchResult’s finalResult property. Within the completion

handler, you update the venues property and reload the table view.

Chapter 5 : NSFetchedResultsController

var fetchedResultsController: NSFetchedResultsController<Team>!

let fetchRequest: NSFetchRequest<Team> = Team.fetchRequest()
let zoneSort = NSSortDescriptor(key: #keyPath(Team.qualifyingZone), ascending: true)
let scoreSort = NSSortDescriptor(key: #keyPath(Team.wins), ascending: true)
let nameSort = NSSortDescriptor(key: #keyPath(Team.teamName), ascending: true)
fetchRequest.sortDescriptors = [zoneSort, scoreSort, nameSort]
        
fetchedResultsController = 
NSFetchedResultsController(fetchRequest: fetchRequest, 
                           managedObjectContext: coreDataStack.managedContext, 
                           sectionNameKeyPath: #keyPath(Team.qualifyingZone),
                           cacheName: "worldCup")
fetchedResultsController.delegate = self

func numberOfSections(in tableView: UITableView) -> Int {
    guard let sections = fetchedResultsController.sections else {
      return 0
    }
    return sections.count
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    guard let sectionInfo = fetchedResultsController.sections?[section] else    {
      return 0
    }
    return sectionInfo.numberOfObjects
 }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: teamCellIdentifier, for: indexPath)
    let team = fetchedResultsController.object(at: indexPath)
    cell.flagImageView.image = UIImage(named: team.imageName!)
    cell.teamLabel.text = team.teamName
    cell.scoreLabel.text = "Wins: \(team.wins)"

    return cell
  }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271

推荐阅读更多精彩内容

  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 13,305评论 5 6
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 8,592评论 0 23
  • 我希望每天早上一觉醒来跟我道早安的人是你,我希望每天跟我一起吃早饭的人是你,我希望每天催我快一点的人是你,我更...
    柔情似你阅读 154评论 0 0
  • 瘾在我们生活中如影随形,比如说烟瘾,酒瘾,手机瘾等. 如果隔一段时间没做这件事情,浑身上下都不舒服,难以忍受。 老...
    野里拐阅读 240评论 0 0