Home > Software design >  Objective C Hashable object for Diffable Data Source
Objective C Hashable object for Diffable Data Source

Time:11-28

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?

  • - (BOOL)isEqual:(id)object
  • - (NSUInteger)hash
  • - (NSComparisonResult)compare:(MyItemType *)other

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

CodePudding user response:

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):

  • == calls -isEqual:, default -isEqual: compares self pointers,
  • hashValue calls -hash, default -hash returns self pointer (cast to NSUInteger).

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

Some good links:

  • Related