TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Is it ok to call Published properties from an ObservableObject class in other classes in Swift

Forums > Swift

Hi, a Service class where I process all Core Data transactions for a single entity/Object and I often find my self needing to access information from other classes and I was wondering if there was an issue by calling these classes in non-UI related classes.

In the following code I'm calling the dogs array from the DogService class inside the DogHouseService class, and I was wondering if this could be an issue.

Are there any possible issue by calling @Published properties from an ObservableObject class inside other classes?

ObservableObject class

 class DogService: ObservableObject{

    let manager: CoreDataManager

    @Published var dogs: [Dog] = []

    init(coreDataManager: CoreDataManager = .instance){
      self.manager = coreDataManager
      loadDogs()
    }

    //Adds, Deletes, Updates, etc.

    func loadDogs(){
      let request = NSFetchRequest<Dog>(entityName: "Dog")
      do{
        dogs =  try manager.context.fetch(request)
      }catch let error{
        print("Error fetching dogs. \(error.localizedDescription)")
      }
    }

    func save(){
      self.manager.save()
    }
  }

Other Class

  class DogHouseService{
    let dogService = DogService()

    for dog in dogService.dogs{
      // do something
    }
  }

2      

Thank you for the clearification. I was concerned with the fact that the dogs is a @Published property, which was desigend to notified/refresh UI components. FYI - The dogs array will only be read from other classes; not modified. Thanks a lot.

2      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.