9

I have a NSViewController managing a NSTableView and noticed that NSViewController has a representedObject property, however it isn't an IBOutlet and I'm not able to bound the dataSource of NSTableView to the representedObject property of NSViewController in interface builder. How is representedObject property suppose to be used? Are there any examples of proper usage?

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
Tony
  • 36,591
  • 10
  • 48
  • 83

2 Answers2

4

The representedObject property should be set to an object that lives outside of the nib, such as the document, another model-controller, or a model object. Things in the nib should get the data from the VC or the VC's representedObject.

Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
  • Hmm, what's the best way to get a reference to the ViewController from objects initialized by the nib? (in other words, how do you get to file's owner from inside code? – Tony Dec 27 '11 at 01:58
  • 1
    @Tony: Give them a reference to it, either by connecting an outlet or setting up a binding. – Peter Hosey Dec 27 '11 at 02:28
1

I know this is an old topic, but I thought I'd add to it as I did quite a bit of research into representedObject. Hope this helps!

representedObject is a reference to some AnyObject (NSObject) that the view should represent.

It's NOT a copy of the object, but rather a reference to it (both in Swift and Objective-C)

Ideally speaking, if the view in question is a page out a "contacts app". This page represents a contact then the representedObject should be set to fooContact by the object that instantiated it. fooContact being a reference to an instance of the contact in question.

It doesn't have to be set by the instantiating class, but personally I find it a cleaner approach to things.

I generally avoid trying to override the default getters/setters of the representedbject and reference it by another var in the class i.e.

weak var document: Document{
    if let docRef = self.representedObject as Document {
        return docRef
    }
    return nil
}

maintaining the weak reference will avoid reference cycles.

Adrian Sluyters
  • 2,186
  • 1
  • 16
  • 21
  • 4
    You cannot use weak ref like that, you cannot return nil either. All your code can be deducted to returning representedObject casted to Document? weak var document: Document? { return representedObject as? Document } – pronebird Aug 30 '15 at 13:06
  • 1
    I was going to say the same thing. It should be a guard-let with a preconditionFailure (or simply a fatalError). If it was a case where you want to return an optional, then a simple `return self.representedObject as? Document` would suffice, no if-let or guard-let needed. – Mark A. Donohoe Apr 16 '18 at 14:49