我正在一个项目中,该项目应该使用GCD同时从不同的服务器URL获取数据。它通过从服务器获取数据并更新视图来按预期工作。

连接控制器:

    private func initiateObjects() {
        self.stationCounter = 1
        self.request = StationRequests()
        self.object  = StationObject()
    }

    private func initiateRequests() {
        request = StationRequests(self.stationCounter)
        request.object = self.object
        request.delegate = self
    }

    private func sendRequest() {
        queueStation.async {
            self.request.SendRequest()
        }
    }

    private func updateView(_ obj: BaseObject?) {
        DispatchQueue.main.async {
            NotificationCenter.default.post(name: .dataFetched, object: nil, userInfo: ["item": obj ?? BaseObject()])
        }
    }

    func managerDidReceived(data: Any, request: BaseRequest) {
        let parsedObj = request.object?.Parse(data)
        self.updateView(parsedObj)
    }


视图控制器:

    override func viewDidLoad() {
        super.viewDidLoad()

        self.initiateStationListService()
    }

    private func initiateStationListService() {
        self.connection.initiate()
        NotificationCenter.default.addObserver(self, selector: #selector(self.dataFetched(_:)), name: .dataFetched, object: nil)
    }

    @objc func dataFetched(_ notification: Notification) {
        guard let items = notification.userInfo as? [String:StationObject] else { return }
        guard let item = items["item"] else { return }
        self.stationList.append(item) //HERE IS THE PROBLEM
        self.collectionView?.reloadData()
    }


问题是,当我想将获取的对象追加到列表中以显示在CollectionView中时,列表项全部更改为最新项。我的意思是,所有先前添加的项目都与最新的项目相同且相同。因此,当我重新加载CollectionView时,所有记录都是相同的。加载的项目本身是正确的,并且没有问题。

最佳答案

请尝试以下方法:

self.stationList += [item]
self.collectionView?.reloadData()

10-04 14:42