0

I have a NSCollectionView where one of the subviews is an NSImageView. The actual image requires loading from a webserver after going through an API call (so actually two network requests). Obviously I need to load the image asynchronously. I can bind the NSImageView's value to an NSValueTransformer that turns the model id into NSImage, but how do I implement the NSValueTransformer? It expects to return immediately from its transformedValue: method, whereas I can only fire off the network request there. I don't want to block the thread using synchronous networking.

1 Answer 1

2

Rather than using a NSValueTransformer which will actually return immediately, subclass the collection view item. For each item fire the transaction in this subclasses asynchronusly. Keep a IBOutlet for the NSImage in your subclass so that when the response is received from the server jus set the Image using this IBOulet. With this approach when the item is created, the corresponding view controller comes into picture. Subclassing it gives you control over the view and how to load it.

I hope this helps.

3
  • OK, when I create the subclass, do I give it its own nib file? Or do I just use the nib where the collection view lives currently? Then, what method do I override to set the image? setValue:forKeyPath: ? How do I connect the bindings to the subclass? Do I have to do it all in code or can I use interface builder?
    – jsd
    Mar 27, 2014 at 14:34
  • You have a itemProtype defined for each Collection View item. Subclass the collection view item, it will pick your itemprototype on its own i.e. nib will take of that. Create a IBOutlet of the NSImageView in this new subclass. in loadView make a call to [super loadView] and call your transaction. Once the data is received in your callback method then set the Image using the IBOutlet's, setImage method. Subclass is only for handling your asynchronus call so in Interface builder jus change the class for collection view item. I hope you got it. I will add some code if you want. Mar 28, 2014 at 5:40
  • I got it. I had to override setRepresentedObject in the NSCollectionViewItem subclass. Also make sure you reference the view to force it to load from the nib otherwise it's likely the outlets will be nil.
    – jsd
    Mar 28, 2014 at 6:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.