0

I have a property called savedArticles that I would like to observe. As of now, it is declared as a Set as a property of a Controller type object as shown below:

@objc dynamic var savedArticles: Set<Article> = []

This does not work because "property cannot be marked @objc because its type cannot be represented in Objective-C".

How should I changed savedArticles so that it can still be used as a set but also be observable?

My first thought was to change the type of my property to NSSet but I couldn't manage to get this working and wasn't even sure if it was the right approach or not. Using this approach, I was forced to manually implelemnt the Hashable protocol for Article. I did that as follows

class Article: Hashable {
    static func == (lhs: Article, rhs: Article) -> Bool {
        return lhs.title == rhs.title && lhs.date == rhs.date && lhs.author == rhs.author
    }
    func hash(into hasher: inout Hasher) {
        title.hash(into: &hasher)
        date.hash(into: &hasher)
        author.hash(into: &hasher)
    }

    var title: String?
    var author: String?
    var description: String?
    var date: String?
}
  • 1
    A KVO observable set is a pretty bad idea, but the discussion in the links will elucidate. It would better to explain to us what problem you are really trying to solve. – matt Dec 24 '19 at 03:23
  • @matt Thanks for the feedback. Sorry for the bad post. If you have time I would like to hear your advice. I have a class called `ArticleController`. In this class I have a property called `savedArticles` (a set). A view controller called `SavedArticlesTableViewController` wants to know about any time a new article is saved so that it can refresh its table. I suppose I could accomplish this by sending a simple notificaiton. So, I observe any changes to `savedArticles`, and my observer (the table view) reloads itself. – Drawkcab Esrever Dec 24 '19 at 03:32
  • 1
    Well so why not use a setter observer? What do you need KVO for? Or why not make the variable private and make the setter public? – matt Dec 24 '19 at 03:35
  • thank you. And I just realized who you are and just want to say I love your books. I preordered Diving Deep into Ios13 on amazon. – Drawkcab Esrever Dec 24 '19 at 03:37

0 Answers0