macoscocoaappkitnscollectionviewnscollectionviewitem

NSCollectionView doesn't seem to need registering its item class


When I made NSCollectionView UI...

First time, I registered my collection view item class using

self.cv.register(NSNib.init(nibNamed: "ContentItemOneClass", bundle: nil), forItemWithIdentifier: "ContentItemOneClass")

and I added more collection views and forget to call like

self.cv.register(NSNib.init(nibNamed: "ContentItemTwoClass", bundle: nil), forItemWithIdentifier: "ContentItemTwoClass")

but collectionView(_:itemForRepresentedObjectAt:) , makeItem(withIdentifier:"ContentItemTwoClass", for: indexPath) seems to work just fine.

Now I wonder if registering classes is necessary or can be removed.

thanks.


Solution

  • Apple has a sample application called CocoaSlideCollection that demonstrates the use of the modern (i.e. 10.11+) NSCollectionView. In the collectionView:itemForRepresentedObjectAtIndexPath: method in the file AAPLBrowserWindowController.m, there is this comment:

    Message back to the collectionView, asking it to make a @"Slide" item associated with the given item indexPath. The collectionView will first check whether an NSNib or item Class has been registered with that name (via -registerNib:forItemWithIdentifier: or -registerClass:forItemWithIdentifier:). Failing that, the collectionView will search for a .nib file named "Slide". Since our .nib file is named "Slide.nib", no registration is necessary.

    While I didn't see this explicitly mentioned in the documentation, this suggests that as long as the .xib name matches the identifier (and has one and only one NSCollectionViewItem or subclass of in the file), then registration isn't needed.