Elita
Elita

Reputation: 77

Grand Central Dispatch

I want to speed my code just a little bit. This is my code:

var loadedText : NSAttributedString = NSAttributedString(string: "")
let changeThemeDispatchGroup = DispatchGroup()
DispatchQueue.global(qos: .userInteractive).async {

    if self.selectedNote.content != nil
    {
        changeThemeDispatchGroup.enter()
        loadedText = self.selectedNote.content as! NSAttributedString
        changeThemeDispatchGroup.leave()
    }
    else
    {
        self.noteTextView.becomeFirstResponder()
    }


    DispatchQueue.main.async
    {
        self.noteTextView.attributedText = loadedText

    }

    changeThemeDispatchGroup.notify(queue: DispatchQueue.main)
    {
        self.changeLetterColor()
    }
}

I'm loading loadedText from database and I'm updating the text view. After updating the textview I'm changing the color of each letter. It works great. But now, I want to load loadedText from the database, change the text color and then update the text view. Can you help me out?

Upvotes: 0

Views: 84

Answers (1)

vadian
vadian

Reputation: 285082

Forget the group and change the order

var loadedText = NSAttributedString(string: "")
DispatchQueue.global(qos: .userInteractive).async {

    if let content = self.selectedNote.content as? NSAttributedString {
        loadedText = content 
    } else {
        self.noteTextView.becomeFirstResponder()
    }

    DispatchQueue.main.async {
       self.changeLetterColor()            
       self.noteTextView.attributedText = loadedText
    }
}

Upvotes: 1

Related Questions