Home > Software engineering >  How to make sure a line of code is run after another has completed?
How to make sure a line of code is run after another has completed?

Time:02-10

I tried to make the last two lines of this code run after the ones before them but they have always run first! Please help.

PostAPI.getPostById(postId: self.postId) { postResponse in
        let post = postResponse
        self.posts[indexPath.row] = post
        let cellNumber = IndexPath(row: indexPath.row, section: indexPath.section)
        self.postsTableView.reloadRows(at: [cellNumber], with: .none)
        likesButton?.tintColor = .systemPink
        likesButton?.setImage(UIImage(systemName: "heart.fill"), for: .normal)
    }

CodePudding user response:

If DispatchQueue.main.async didnt work maybe you can try a function with completion

PostAPI.getPostById(postId: self.postId) { postResponse in
    self.reloadThenLike {
        self.likesButton?.tintColor = .systemPink
        self.likesButton?.setImage(UIImage(systemName: "heart.fill"), 
            for: .normal)
    }
}

func reloadThenLike(completion: @escaping () -> ()) {
    let post = postResponse
    self.posts[indexPath.row] = post
    let cellNumber = IndexPath(row: indexPath.row, section: 
        indexPath.section)
    self.postsTableView.reloadRows(at: [cellNumber], with: .none)
    completion()
}

CodePudding user response:

Maybe try reloading the table view using CATransaction

1. Create a table view extension to add completion to rows reload

extension UITableView
{
    func reloadRows(at indexPaths: [IndexPath],
                    with animation: UITableView.RowAnimation,
                    completion: (() -> Void)?)
    {
        CATransaction.begin()
        CATransaction.setCompletionBlock(completion)
        reloadRows(at: indexPaths, with: animation)
        CATransaction.commit()
    }
}

Then try adjusting your code to use it as follows

PostAPI.getPostById(postId: self.postId) { postResponse in
    let post = postResponse
    self.posts[indexPath.row] = post
    let cellNumber = IndexPath(row: indexPath.row, section: indexPath.section)
    
    // Reload the table view with completion handler
    self.postsTableView.reloadRows(at: [cellNumber], with: .none) { [weak self] in
        
        // Reload complete, do your work
        self?.likesButton?.tintColor = .systemPink
        self?.likesButton?.setImage(UIImage(systemName: "heart.fill"), for: .normal)
        
    }
}

Give this a go and see if this helps you

  • Related