如何正确地将对象插入数组(回调后)?

时间:2016-05-26 23:23:29

标签: ios swift

我想将User对象追加到数组中。但是,我只想在下载数据之后这样做。

var items = [User]()
for id in user_ids {
    let user = User(id: id)
    user.downloadData({ [weak self] in
        items.append(user) //will "user" be THIS instance?
    })
}

订购很重要。我也不希望任何复杂的复杂等等。

将一个实例插入到同一个实例的回调中的数组中,这让我想知道我是否正确地进行了操作。

我是否正确地做到了?

1 个答案:

答案 0 :(得分:1)

是的,它是同一个用户。但是,并不能保证每个用户都按照您启动它的顺序完成。进行2次更改:(1)使用字典存储下载的数据;(2)使用Grand Central Dispatch等待所有下载的数据:

// Assume user's ID is an Int
let userData = [Int: User]()
let groupID = dispatch_group_create()

for id in user_ids {
    let user = User(id: id)
    dispatch_group_enter(groupID)

    user.downloadData{ [weak self] in
        userData[id] = user
        dispatch_group_leave(groupID)
    }
}

// Wait until data for all users have been downloaded
dispatch_group_wait(groupID, DISPATCH_TIME_FOREVER)

// Now all users' data have been downloaded. If you want to put them
// into an array according to some order, do this:
let items = user_ids.map { userData[$0]! }