iosobjective-cuicollectionviewdiffabledatasourceuicollectionviewdiffabledatasource

Objective-C Hashable object for Diffable Data Source


I am trying to implement a collection view with a diffable data source in Objective-C. I know for Swift, the generic types for UICollectionViewDiffableDataSource are types that conform to both the Hashable and Identifiable protocols. But I do not know what these correspond to for Objective-C.

So my question is if I have a data source property like so:

@property (strong, nonatomic) UICollectionViewDiffableDataSource<NSString *, MyItemType *> *dataSource;

Then what do I need to implement in MyItemType to make it work correctly? Is it sufficient to just implement the following methods or are these not correct and I need to implement something else for Objective-C?

And what protocol(s) do I need to adopt for my model object?

MyItemType.h

Here is the definition of the model item. These are displayed in a collection view list layout.

@interface MyItemType : NSObject

@property (strong, nonatomic) NSString *title;
@property (strong, nonatomic, nullable) NSString *subtitle;
@property (strong, nonatomic, nullable) NSArray<MyItemType *> *children;
@property (strong, nonatomic, nullable) UIImage *image;

@end

Solution

  • From the declaration:

    class UICollectionViewDiffableDataSource<SectionIdentifierType, ItemIdentifierType> : NSObject where SectionIdentifierType : Hashable, ItemIdentifierType : Hashable
    

    ItemIdentifierType must only be Hashable. NSObject already conforms to Hashable, but, by default it only compares instance identity (e.g. pointer):

    For MyItemType, being a subclass of NSObject it is sufficient to only override -isEqual: and -hash.

    Some good links: