How to use CoreData in Xcode 8?

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

- (NSPersistentContainer *)persistentContainer 

and

 - (void)saveContext 

Now I canโ€™t use the old methods to work with CoreData , and I canโ€™t find tutorials with these new methods and Objective-C. How to save and retrieve data from CoreData using persistentContainer in Xcode 8 using Objective-c?

+5
source share
3 answers

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 extract the data , for example -

 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 select 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 -

 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 keep the context -

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

or as in Objective-C

 [((AppDelegate*)[[UIApplication sharedApplication] delegate]) saveContext]; 
+15
source
 -(void)profileDatabase 

{NSManagedObjectContext * context = [ADM.persistentContainer viewContext];

 NSManagedObject *profile=[NSEntityDescription insertNewObjectForEntityForName:@"Profile" inManagedObjectContext:context]; [profile setValue:[self.serverResponseOfProfileDict objectForKey:@"firstName"] forKey:@"firstName"]; [profile setValue:[self.serverResponseOfProfileDict objectForKey:@"surName"] forKey:@"surName"]; [profile setValue:[self.serverResponseOfProfileDict objectForKey:@"batchID"] forKey:@"batchID"]; [profile setValue:[self.serverResponseOfProfileDict objectForKey:@"profileImagePath"] forKey:@"profileImagePath"]; [profile setValue:[self.serverResponseOfProfileDict objectForKey:@"registeredEmail"] forKey:@"registeredEmail"]; [profile setValue:[self.serverResponseOfProfileDict objectForKey:@"role"] forKey:@"role"]; [profile setValue:[self.serverResponseOfProfileDict objectForKey:@"studentID"] forKey:@"studentID"]; NSLog(@"userObj:%@",profile); NSError* error; [context save:&error]; NSFetchRequest *fetchRequest=[[NSFetchRequest alloc]initWithEntityName:@"Profile"]; fetchRequest.returnsObjectsAsFaults=NO; NSArray* results=[context executeFetchRequest:fetchRequest error:&error]; NSLog(@"Result:%@",results); NSManagedObject *result=[results objectAtIndex:0]; [ADM.databaseResponseOfProfileDict setObject:[result valueForKey:@"firstName"] forKey:@"firstName"]; [ADM.databaseResponseOfProfileDict setObject:[result valueForKey:@"surName"] forKey:@"surName"]; [ADM.databaseResponseOfProfileDict setObject:[result valueForKey:@"batchID"] forKey:@"batchID"]; [ADM.databaseResponseOfProfileDict setObject:[result valueForKey:@"profileImagePath"] forKey:@"profileImagePath"]; [ADM.databaseResponseOfProfileDict setObject:[result valueForKey:@"registeredEmail"] forKey:@"registeredEmail"]; [ADM.databaseResponseOfProfileDict setObject:[result valueForKey:@"role"] forKey:@"role"]; [ADM.databaseResponseOfProfileDict setObject:[result valueForKey:@"studentID"] forKey:@"studentID"]; NSLog(@"dic:%@",ADM.databaseResponseOfProfileDict); 

}

+3
source

I found a solution using Objective C. It works, but I'm not sure if this is the right solution.

 - (void)dbManager { NSManagedObjectContext *context = self.persistentContainer.viewContext; NSError *error = nil; if ([context hasChanges] && ![context save:&error]) { // Replace this implementation with code to handle the error appropriately. // abort() 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. NSLog(@"Unresolved error %@, %@", error, error.userInfo); abort(); } NSManagedObject *customAnimal = [NSEntityDescription insertNewObjectForEntityForName:@"Animals" inManagedObjectContext:context]; [customAnimal setValue:@"Lion" forKey:@"type"]; [customAnimal setValue:@"Rabit" forKey:@"name"]; [customAnimal setValue:@"Blue" forKey:@"color"]; [customAnimal setValue:@12 forKey:@"age"]; NSLog(@"Get data from DB"); NSMutableArray* animalsArray; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Animals"]; animalsArray = [[context executeFetchRequest:fetchRequest error:nil] mutableCopy]; NSLog(@"array is %@", animalsArray); // array is ( "<Animals: 0x6000000aee80> (entity: Animals; id: 0x60000022e120 <x-coredata:///Animals/tAAC7332D-6BEF-441C-9041-0ECB57469FA62> ; data: {\n age = 12;\n color = Blue;\n name = Rabit;\n type = Lion;\n})" 

}

0
source

Source: https://habr.com/ru/post/1260991/


All Articles