Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

swift - Environmentobject keep track of arrays variables

I'm pretty new to xCode so this could have an obvious answer.
I've just learned about environment objects and created the following one:

import SwiftUI

class Data: ObservableObject {
    @Published var types = [Type]()
    @Published var customers = [Customer]()
    @Published var templates = [SubscriptionTemplate]()
    @Published var subscriptions = [Subscription]()
    @Published var giftCodes = [Giftcode]()
}

As you can see the object contains an array of objects. One of these is a customer array. The customer object looks like this:

import SwiftUI

class Customer: Identifiable, Codable{
    var id: Int
    var firstname: String
    var lastname: String
    var address: String
    var plz: Int
    var place: String
    var credit: Int
    
    init(id: Int, firstname: String, lastname: String, address: String, plz: Int, place: String, credit: Int) {
        self.id = id
        self.firstname = firstname
        self.lastname = lastname
        self.address = address
        self.plz = plz
        self.place = place
        self.credit = credit
    }
}

extension Customer: Equatable {
    static func == (lhs: Customer, rhs: Customer) -> Bool {
        return lhs.id == rhs.id
    }
}

In my project, I implemented an API call to update the customer. This works like a charm, but after updating, I also want to fetch the customer objects with the following method:

API().fetchCustomers { (customers) in
    self.data.customers = customers
}

After updating an object this doesn't work. The environment object doesn't update, but after creating a new object or fetching the data initial, it works.

What is the difference between the update and the create / fetch?

question from:https://stackoverflow.com/questions/65644795/environmentobject-keep-track-of-arrays-variables

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Make Customer a value type (ie. struct):

struct Customer: Identifiable, Codable{
    var id: Int

   // ... other code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...