How to use CoreData in Xcode 8?

scorpio picture scorpio · Dec 8, 2016 · Viewed 7.6k times · Source

I am trying use CoreData, but when I add it to my project I only get two new methods :

- (NSPersistentContainer *)persistentContainer

and

- (void)saveContext

Now I can't get old methods to work with CoreData, and I can't find any tutorials with these new methods and Objective-C. How can I save and get data from CoreData using persistentContainer in Xcode 8 with Objective-c?

Answer

Nikhil Manapure picture Nikhil Manapure · Dec 8, 2016

You can Get context as -

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

or as in Objective-C

NSManagedObjectContext *context = ((AppDelegate*)[[UIApplication sharedApplication] delegate]).persistentContainer.viewContext;

And fetch data like -

var resultArray  = try self.context.fetch(EntityName.fetchRequest())

or as in Objective-C

NSFetchRequest<EntityName *> *fetchRequest = [EntityName fetchRequest];
NSError *error ;
NSArray *resultArray= [context executeFetchRequest:fetchRequest error:&error];

And fetch data with sorting -

var resultArray = [EntityName]()
do {
        let request : NSFetchRequest<EntityName> = EntityName.fetchRequest()
        let sortDescriptor = NSSortDescriptor(key: "somekey", ascending: true)
        let sortDescriptors = [sortDescriptor]
        request.sortDescriptors = sortDescriptors
        resultArray = try self.context.fetch(request)
} catch {
        print("Error")
}

or as in Objective-C

NSFetchRequest<EntityName *> *fetchRequest = [EntityName fetchRequest];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"someKey" ascending:YES];
fetchRequest.sortDescriptors = @[sortDescriptor];
NSError *error ;
NSArray *resultArray= [context executeFetchRequest:fetchRequest error:&error];

And add data like -

let entityNameObj = EntityName(context: context)
entityNameObj.title = "title"

or as in Objective-C

NSManagedObject *entityNameObj = [NSEntityDescription insertNewObjectForEntityForName:@"EntityName" inManagedObjectContext:context];
[entityNameObj setValue:@"someValue" forKey:@"someKey"];

And save context like -

do {
     try self.context.save()
} catch _ as NSError {
     print("Error")
}

or as in Objective-C

[((AppDelegate*)[[UIApplication sharedApplication] delegate]) saveContext];