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:
comparesself
pointers,hashValue
calls-hash
, default-hash
returnsself
pointer (cast toNSUInteger
).
For MyItemType
, being a subclass of NSObject
it is sufficient to only override -isEqual:
and -hash
.
Some good links:
- https://www.mikeash.com/pyblog/friday-qa-2010-06-18-implementing-equality-and-hashing.html
- https://nshipster.com/equality/
- "Using Swift with Cocoa and Objective-C" book in Apple Books