如何覆盖 isEqual: CLBeacon?

How to override isEqual: for CLBeacon?

背景

我有一个方法,由第 3 方库提供,returns 一个 CLBeacons 的数组。

- (void)beaconManager:(ESTBeaconManager *)manager
      didRangeBeacons:(NSArray *)beacons
             inRegion:(CLBeaconRegion *)region

定期调用此方法,数组包含范围内的信标列表。数组中的对象不被重复使用,每次发送新的信标对象

我正在根据它们的接近程度向数组中添加和删除这些对象。


问题

如何为 CLBeacon 实现 isEqual:,以便 containsObject:removeObject: 等数组方法无需大量额外实现即可工作。

我不能 subclass,因为 CLBeacon 作为 CLBeacon 返回,我不能只将它转换为我的自定义 class。

我无法编写类别,因为在运行时调用的 isEqual: 是未定义的。

If the name of a method declared in a category is the same as a method in the original class, or a method in another category on the same class (or even a superclass), the behavior is undefined as to which method implementation is used at runtime. This is less likely to be an issue if you’re using categories with your own classes, but can cause problems when using categories to add methods to standard Cocoa or Cocoa Touch classes.

[Source]

我真的不想求助于 method swizzling。

创建一个全局函数 beaconsAreEqual,它将 2 个 CLBeacon 作为输入,returns 一个布尔值。

或者您是否特别需要定义 isEqual 方法?如果是这样,您可能必须使用方法调配。

编辑:

或者,您可以创建一个 CLBeacon 的自定义子class 来覆盖 isEqual(如果您想使用 NSArray 方法,可能还有散列 contains

然后为您的 class 创建一个自定义初始化器,它将常规 CLBeacon 作为输入并复制相关信息(您只需要 UUID、主要和次要版本号。)

完成后,您可以获取来自位置管理器的信标,将它们转换为您的自定义 class,并将这些保存到您的数组中并将它们用于您的 contains 检查。

编辑#2:

另一种选择是使用 NSArray 方法 indexOfObjectPassingTest 而不是。该方法将一个块作为参数,returns 一个整数索引,如果找不到对象则使用 NSNotFound。

编辑#3:

好像没有自己创建CLBeacon对象的初始化器。您必须创建一个数据容器对象(NSObject 的 subclass)来保存来自 CLBeacon 的信息。这对于检查信标是否已经在您的数组中非常有用