fetchRequest.sortDescriptors = [NSSortDescriptor(key: “id”, ascending: true, selector: “localizedStandardCompare:” )]

What’s new in Core Data Swift 3.0 https://blog.jayway.com/2016/08/12/whats-new-core-data-swift-3-0/

Beginner Guide to Core Data in Swift

https://www.bobthedeveloper.io/blog/beginner-guide-to-core-data-in-swift

Getting Started with Core Data Tutorial

https://www.raywenderlich.com/173972/getting-started-with-core-data-tutorial-2

CSV reading and writing library written in Swift. (3rd party library docs)

https://github.com/yaslab/CSV.swift#usage-for-reading-csv

my review point is 9/10

chatting app의 메시지 표시창 구성의 기본을 알수 있음.

https://youtu.be/hz1h_ColGy0?t=5m29s   NSDate()을 이용한 시간 변경

https://youtu.be/hz1h_ColGy0?t=7m   core data sorting

https://youtu.be/hz1h_ColGy0?t=8m   core data predicate 

https://youtu.be/hz1h_ColGy0?t=14m45s   array sort (using ‘compare’ method )

https://youtu.be/hz1h_ColGy0?t=17m10s   collection view controller에서 cell을 선택한 경우 다른 controller로 연결되게 하는 작업 (programticallay)

https://youtu.be/hz1h_ColGy0?t=20m10s   collection view 내용, 모양 변경 (programmatically)

오래전에 만들어진 tutorial이나 블로그 포스트를 보면 요즘(2018 6 10) 과 appdelegate에 있는 코드가 다른것을 알수 있다. 최근의 코드에서는 persistentContainer 를 통해 managedObjectContext, managedObjectModel, persistentStoreCoordinator 에 접근할수 있게 되었다.

최근)

// MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "test")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                 
                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error (error), (error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error (nserror), (nserror.userInfo)")
            }
        }
        
        
    }



예전)

import CoreData
class CoreDataStack {
    // Applications default directory address
    lazy var applicationDocumentsDirectory: NSURL = {
        let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
        return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
        // 1
        let modelURL = NSBundle.mainBundle().URLForResource("Supercars", withExtension: "momd")!
        return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
        let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
        let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SuperCars.sqlite")
        do {
            // If your looking for any kind of migration then here is the time to pass it to the options
            try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
        } catch let  error as NSError {
           print("Ops there was an error (error.localizedDescription)")
           abort()
        }
        return coordinator
}()

lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the
application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to
fail.
        let coordinator = self.persistentStoreCoordinator
        var context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
        context.persistentStoreCoordinator = coordinator
        return context
}()
// if there is any change in the context save it
func saveContext() {
        if mangagedObjectContext.hasChanges {
            do {
                try managedObjectContext.save()
            } catch let error as NSError {
                print("Ops there was an error (error.localizedDescription)")
                abort() 
      }
     } 
   }
}

core data blog posts by jacobs

튜토리얼 리스트

https://code.tutsplus.com/series/core-data-and-swift–cms-907

core data stack 기본 개념 구조

https://code.tutsplus.com/tutorials/core-data-and-swift-core-data-stack–cms-25065

xcode에서  .xcdatamodeld화일을 editor를 통해 열고 Data Model 를 만들고 수정하는 방법 설명

https://code.tutsplus.com/tutorials/core-data-and-swift-data-model–cms-25067

managed object(record) create, delete, fetch, update 하는 방법과 간단한 faulting으로 메모리 절약하는 방법 설명

https://code.tutsplus.com/tutorials/core-data-and-swift-managed-objects-and-fetch-requests–cms-25068

relationship 으로 연결된 managed object를 추가하는 방법과 sorting과 predicates이 첨가된 fetch방법 설명

https://code.tutsplus.com/tutorials/core-data-and-swift-relationships-and-more-fetching–cms-25070

core data 사용 실예에 대한 전반적인 내용  (NSFetchedResultsController 사용 방법 포함)

https://code.tutsplus.com/tutorials/core-data-and-swift-nsfetchedresultscontroller–cms-25072

core data 사용 실예에 대한 전반적인 내용2  (NSFetchedResultsController 사용 방법 포함2)

https://code.tutsplus.com/tutorials/core-data-and-swift-more-nsfetchedresultscontroller–cms-25078

migration 과 migration시 문제 처리방법

https://code.tutsplus.com/tutorials/core-data-and-swift-migrations–cms-25084

subclassing NSManagedObject

https://code.tutsplus.com/tutorials/core-data-and-swift-subclassing-nsmanagedobject–cms-25116

core data concurrency

https://code.tutsplus.com/tutorials/core-data-and-swift-concurrency–cms-25118


core data batch update

https://code.tutsplus.com/tutorials/core-data-and-swift-batch-updates–cms-25120

core data batch delete

https://code.tutsplus.com/tutorials/core-data-and-swift-batch-deletes–cms-25380

asynchronous fetch

https://code.tutsplus.com/tutorials/core-data-and-swift-asynchronous-fetching–cms-25123


core data by graig (youtube)

https://youtu.be/2idtKQ_NqTs    Introduction – Beginning Core Data

https://youtu.be/PMze4tT2w_U    – Getting Started – Beginning Core Data

https://youtu.be/62A-zAzc0aE    – NSManagedObject Subclasses – Beginning Core Data

4:16 에 나오는 코드 부분 개요

tab controller 그다음 navigation controller 그 안에서 제일 위의 top controller 에 접근한다. 그리고 respondsToSelector()를 통해 그안에 setManagedObjectContext() 가 있는지 확인하고 있으면 performSelector()를 이용 그 함수를 수행한다.

참고) http://weimenglee.blogspot.com/2014/09/swift-checking-if-method-exists.html

https://youtu.be/kNztJgGbQTM    – Editing and Deleting Data – Beginning Core Data

https://youtu.be/uJuLk1niBYA    -Relationships – Beginning Core Data

https://youtu.be/oK1K5h5EbZY    – Predicates and Sorting – Beginning Core Data

https://youtu.be/hRBr1mLZFaY    -Conclusion – Beginning Core Data

https://youtu.be/pp0zOJZcYhI    – Introduction – Intermediate Core Data

https://youtu.be/lMT96wUsjMQ    – Managed Object Contexts – Intermediate Core Data

https://youtu.be/lMT96wUsjMQ   – Conclusion – Intermediate Core Data

https://youtu.be/ZRwXbb1cOFw   -fetched result controller

NSManagedObject를 직접이용 core data 를 이용 managed objects 를 만들고 add,  fetch 하는 과정 (이렇게 사용하는 경우의 문제를 보완하는 것이 NSManagedObject를 subclassing 해서 사용하는 것이다. https://youtu.be/62A-zAzc0aE )

만들고 add 하는 과정

image

fetch하는 과정

image