@@ -9,24 +9,34 @@ import UIKit
99import CoreData
1010
1111protocol CoreDataContract : AnyObject {
12+ var delegate : [ UpdateDelegateProtocol ] { get set }
13+ var favoriteAnimals : [ FavoriteAnimal ] { get set }
1214 func loadFavoriteAnimals( completion: @escaping ( ) -> ( ) )
1315 func isFavorite( id: String ) -> Bool
1416 func addFavorite( _ animal: Animal )
1517 func removeFavorite( id: String )
1618 func saveChanges( )
1719}
1820
21+ protocol UpdateDelegateProtocol : AnyObject {
22+ func updateFavoriteAnimals( )
23+ }
24+
1925class CoreData : CoreDataContract {
20- var managedContext : NSManagedObjectContext ?
21- static var favoriteAnimals = [ FavoriteAnimal] ( ) {
26+ static let shared = CoreData ( )
27+
28+ private var managedContext : NSManagedObjectContext ?
29+
30+ var delegate = [ UpdateDelegateProtocol] ( )
31+ var favoriteAnimals = [ FavoriteAnimal] ( ) {
2232 didSet {
23- notifyChanges ? ( )
33+ delegate. forEach { delegate in
34+ delegate. updateFavoriteAnimals ( )
35+ }
2436 }
2537 }
2638
27- static var notifyChanges : ( ( ) -> Void ) ?
28-
29- init ( ) {
39+ private init ( ) {
3040 managedContext = ( UIApplication . shared. delegate as? AppDelegate ) ?
3141 . persistentContainer
3242 . viewContext
@@ -38,7 +48,7 @@ class CoreData: CoreDataContract {
3848 let fetchRequest : NSFetchRequest < FavoriteAnimal > = FavoriteAnimal . fetchRequest ( )
3949
4050 do {
41- CoreData . favoriteAnimals = try managedContext. fetch ( fetchRequest)
51+ self . favoriteAnimals = try managedContext. fetch ( fetchRequest)
4252 completion ( )
4353 } catch let error as NSError {
4454 print ( " Could not fetch. \( error) , \( error. userInfo) " )
@@ -47,7 +57,7 @@ class CoreData: CoreDataContract {
4757
4858 func isFavorite( id: String ) -> Bool {
4959
50- for animal in CoreData . favoriteAnimals {
60+ for animal in self . favoriteAnimals {
5161 if animal. id == id {
5262 return true
5363 }
@@ -66,7 +76,7 @@ class CoreData: CoreDataContract {
6676 newFavoriteAnimal. descript = animal. description
6777 newFavoriteAnimal. age = Int32 ( animal. age ?? 0 )
6878 newFavoriteAnimal. species = animal. species
69- CoreData . favoriteAnimals. append ( newFavoriteAnimal)
79+ self . favoriteAnimals. append ( newFavoriteAnimal)
7080 }
7181
7282 func removeFavorite( id: String ) {
@@ -75,10 +85,10 @@ class CoreData: CoreDataContract {
7585
7686 var count = 0
7787
78- for animal in CoreData . favoriteAnimals {
88+ for animal in self . favoriteAnimals {
7989 if animal. id == id {
8090 let removeAnimal = animal
81- CoreData . favoriteAnimals. remove ( at: count)
91+ self . favoriteAnimals. remove ( at: count)
8292 managedContext. delete ( removeAnimal)
8393 }
8494 count += 1
0 commit comments