我正在嘗試使用 Objective C 中的可區分資料源實作集合視圖。我知道對于 Swift, UICollectionViewDiffableDataSource 的通用型別是符合 Hashable 和 Identifiable 協議的型別。但我不知道這些對應于 Objective C 的內容。
所以我的問題是我是否有這樣的資料源屬性:
@property (strong, nonatomic) UICollectionViewDiffableDataSource<NSString *, MyItemType *> *dataSource;
那么我需要實施什么MyItemType才能使其正常作業?僅實作以下方法就足夠了,還是這些方法不正確,我需要為 Objective C 實作其他方法?
- (BOOL)isEqual:(id)object- (NSUInteger)hash- (NSComparisonResult)compare:(MyItemType *)other
我的模型物件需要采用什么協議?
我的專案型別.h
這是模型項的定義。這些顯示在集合視圖串列布局中。
@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
uj5u.com熱心網友回復:
從宣告:
class UICollectionViewDiffableDataSource<SectionIdentifierType, ItemIdentifierType> : NSObject where SectionIdentifierType : Hashable, ItemIdentifierType : Hashable
ItemIdentifierType只能是可哈希的。NSObject已經符合Hashable,但是,默認情況下它只比較實體標識(例如指標):
==呼叫-isEqual:,默認-isEqual:比較self指標,hashValue呼叫-hash,默認-hash回傳self指標(強制轉換為NSUInteger)。
對于MyItemType,作為NSObject它的子類足以僅覆寫-isEqual:和-hash。
一些不錯的鏈接:
- https://www.mikeash.com/pyblog/friday-qa-2010-06-18-implementing-equality-and-hashing.html
- https://nshipster.com/equality/
- Apple Books 中的“將 Swift 與 Cocoa 和 Objective-C 結合使用”一書
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/368634.html
標籤:ios 目标-c 用户界面 可区分的数据源 uicollectionviewdiffabledatasource
上一篇:獲取IllegalArgumentException:嘗試添加包含AtomicIntegerintredis快取的資料時無法將String轉換為AtomicInteger
