【问题标题】:Objective-C Hashable object for Diffable Data Source用于 Diffable 数据源的 Objective C Hashable 对象
【发布时间】:2021-12-29 16:09:32
【问题描述】:

我正在尝试在 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

我的模型对象需要采用什么协议?

MyItemType.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

【问题讨论】:

    标签: ios objective-c uicollectionview diffabledatasource uicollectionviewdiffabledatasource


    【解决方案1】:

    来自declaration

    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 就足够了。

    一些不错的链接:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-26
      • 2010-10-06
      • 2020-02-18
      • 2016-04-14
      • 2011-01-17
      • 1970-01-01
      相关资源
      最近更新 更多