为什么@Binding属性导致每次都不释放init?

时间:2019-10-12 11:16:35

标签: swiftui combine

这是一整天都让我感到困惑的错误,我为自己的案例做一个演示,所有的只是一个清单和一个细节。

Room.swift

struct Room: Identifiable {

    var id: Int
    var name: String
}

RoomListModel.swift

class RoomListModel: ObservableObject {
    @Published var rooms: [Room] = [
        Room(id: 1, name: "Room A"),
        Room(id: 2, name: "Room B"),
        Room(id: 3, name: "Room C"),
    ]
}

RoomList.swift

struct RoomList: View {

    @ObservedObject var model = RoomListModel()

    var body: some View {

        NavigationView {
            List {
                ForEach(model.rooms.indices) { index in
                    RoomRow(room: self.$model.rooms[index])
                }
            }
            .listStyle( GroupedListStyle() )
        }
    }
}

RoomRow.swift

struct RoomRow: View {

    @Binding var room: Room

    init(room: Binding<Room>) {
        print("initing RoomRow: " + room.name.wrappedValue)
        self._room = room
    }

    var body: some View {
        NavigationLink(
            destination: RoomDetail(room: $room)
        ) {
            Text(room.name)
        }
    }
}

RoomDetail.swift

struct RoomDetail: View {

    @Binding var room: Room

    init(room: Binding<Room>) {
        print("initing RoomDetail: " + room.name.wrappedValue)
        self._room = room
    }

    var body: some View {
        Text(room.name)
    }
}

为方便起见,我在init中添加了打印内容。

加载列表时,所有的RoomRow和RoomDetail都被初始化,确定。

initing RoomRow: Room A
initing RoomDetail: Room A
initing RoomRow: Room B
initing RoomDetail: Room B
initing RoomRow: Room C

但是当我触发RowDetail之一时,所有RoomDetails都再次被初始化,但是我只是转到其中一个,而不是全部,为什么初始化了所有RoomDetails,并且 AGAIN

initing RoomDetail: Room C
initing RoomDetail: Room A
initing RoomDetail: Room B

我不知道为什么,但是找到了一个解决方案,我删除了所有@Binding属性,并且可以,但是为什么 @Binding会导致不相关的初始化?

0 个答案:

没有答案