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閱讀 216,496評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件莺匠,死亡現場離奇詭異,居然都是意外死亡十兢,警方通過查閱死者的電腦和手機趣竣,發(fā)現死者居然都...
    沈念sama閱讀 92,407評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來旱物,“玉大人遥缕,你說我怎么就攤上這事∠海” “怎么了单匣?”我有些...
    開封第一講書人閱讀 162,632評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長宝穗。 經常有香客問我户秤,道長,這世上最難降的妖魔是什么逮矛? 我笑而不...
    開封第一講書人閱讀 58,180評論 1 292
  • 正文 為了忘掉前任虎忌,我火速辦了婚禮,結果婚禮上橱鹏,老公的妹妹穿的比我還像新娘。我一直安慰自己堪藐,他們只是感情好莉兰,可當我...
    茶點故事閱讀 67,198評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著礁竞,像睡著了一般糖荒。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上模捂,一...
    開封第一講書人閱讀 51,165評論 1 299
  • 那天捶朵,我揣著相機與錄音,去河邊找鬼狂男。 笑死综看,一個胖子當著我的面吹牛,可吹牛的內容都是我干的岖食。 我是一名探鬼主播红碑,決...
    沈念sama閱讀 40,052評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了析珊?” 一聲冷哼從身側響起羡鸥,我...
    開封第一講書人閱讀 38,910評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎忠寻,沒想到半個月后惧浴,有當地人在樹林里發(fā)現了一具尸體,經...
    沈念sama閱讀 45,324評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡奕剃,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,542評論 2 332
  • 正文 我和宋清朗相戀三年衷旅,在試婚紗的時候發(fā)現自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片祭饭。...
    茶點故事閱讀 39,711評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡芜茵,死狀恐怖,靈堂內的尸體忽然破棺而出倡蝙,到底是詐尸還是另有隱情九串,我是刑警寧澤,帶...
    沈念sama閱讀 35,424評論 5 343
  • 正文 年R本政府宣布寺鸥,位于F島的核電站猪钮,受9級特大地震影響,放射性物質發(fā)生泄漏胆建。R本人自食惡果不足惜烤低,卻給世界環(huán)境...
    茶點故事閱讀 41,017評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望笆载。 院中可真熱鬧扑馁,春花似錦、人聲如沸凉驻。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽涝登。三九已至雄家,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間胀滚,已是汗流浹背趟济。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留咽笼,地道東北人顷编。 一個月前我還...
    沈念sama閱讀 47,722評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像剑刑,于是被迫代替她去往敵國和親勾效。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,611評論 2 353

推薦閱讀更多精彩內容

  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的閱讀 13,470評論 5 6
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,476評論 0 23
  • 我希望每天早上一覺醒來跟我道早安的人是你,我希望每天跟我一起吃早飯的人是你层宫,我希望每天催我快一點的人是你杨伙,我更...
    柔情似你閱讀 167評論 0 0
  • 癮在我們生活中如影隨形,比如說煙癮萌腿,酒癮限匣,手機癮等. 如果隔一段時間沒做這件事情,渾身上下都不舒服毁菱,難以忍受米死。 老...
    野里拐閱讀 254評論 0 0