@@ -9,6 +9,7 @@ import UIKit
99import CoreData
1010
1111protocol CoreDataContract : AnyObject {
12+ var favoriteAnimals : [ FavoriteAnimal ] { get set }
1213 func loadFavoriteAnimals( completion: @escaping ( ) -> ( ) )
1314 func isFavorite( id: String ) -> Bool
1415 func addFavorite( _ animal: Animal )
@@ -17,16 +18,16 @@ protocol CoreDataContract: AnyObject {
1718}
1819
1920class CoreData : CoreDataContract {
20- var managedContext : NSManagedObjectContext ?
21- static var favoriteAnimals = [ FavoriteAnimal] ( ) {
21+ static let shared = CoreData ( )
22+
23+ private var managedContext : NSManagedObjectContext ?
24+ var favoriteAnimals = [ FavoriteAnimal] ( ) {
2225 didSet {
23- notifyChanges ? ( )
26+ //completar
2427 }
2528 }
2629
27- static var notifyChanges : ( ( ) -> Void ) ?
28-
29- init ( ) {
30+ private init ( ) {
3031 managedContext = ( UIApplication . shared. delegate as? AppDelegate ) ?
3132 . persistentContainer
3233 . viewContext
@@ -38,7 +39,7 @@ class CoreData: CoreDataContract {
3839 let fetchRequest : NSFetchRequest < FavoriteAnimal > = FavoriteAnimal . fetchRequest ( )
3940
4041 do {
41- CoreData . favoriteAnimals = try managedContext. fetch ( fetchRequest)
42+ self . favoriteAnimals = try managedContext. fetch ( fetchRequest)
4243 completion ( )
4344 } catch let error as NSError {
4445 print ( " Could not fetch. \( error) , \( error. userInfo) " )
@@ -47,7 +48,7 @@ class CoreData: CoreDataContract {
4748
4849 func isFavorite( id: String ) -> Bool {
4950
50- for animal in CoreData . favoriteAnimals {
51+ for animal in self . favoriteAnimals {
5152 if animal. id == id {
5253 return true
5354 }
@@ -66,7 +67,7 @@ class CoreData: CoreDataContract {
6667 newFavoriteAnimal. descript = animal. description
6768 newFavoriteAnimal. age = Int32 ( animal. age ?? 0 )
6869 newFavoriteAnimal. species = animal. species
69- CoreData . favoriteAnimals. append ( newFavoriteAnimal)
70+ self . favoriteAnimals. append ( newFavoriteAnimal)
7071 }
7172
7273 func removeFavorite( id: String ) {
@@ -75,10 +76,10 @@ class CoreData: CoreDataContract {
7576
7677 var count = 0
7778
78- for animal in CoreData . favoriteAnimals {
79+ for animal in self . favoriteAnimals {
7980 if animal. id == id {
8081 let removeAnimal = animal
81- CoreData . favoriteAnimals. remove ( at: count)
82+ self . favoriteAnimals. remove ( at: count)
8283 managedContext. delete ( removeAnimal)
8384 }
8485 count += 1
0 commit comments