扩展现有对象(ISA Swizzling?)

Extending existing Object (ISA Swizzling?)

以下问题:我从框架(不可实例化)收到一个对象,我想扩展它。当我创建一个类别时,问题是它对现有对象没有影响。

我想到了 isa swizzling。所以让isa字段指向扩展的"list of selectors"。但这似乎不可能? (它的语法?)

有谁知道更好的方法吗?

也就是代码:

- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray<CBATTRequest *> *)requests {
      //want to do something that uses the extension
}

我想扩展 CBATTRequest。我认为问题出在 CoreBluetooth 上?

这就是我创建类别的方式:

BLERequestable.h

@protocol BLERequestable <NSObject>

- (nonnull NSString *)getCentralUUID;
- (nonnull NSString *)getCharacteristicUUID;
- (nullable NSData*)getData;
- (void)setData:(nullable NSData *) data;

@end

CBATT请求+Requestable.h

#import <CoreBluetooth/CoreBluetooth.h>
#import "BLERequestable.h"

@interface CBATTRequest (Requestable) <BLERequestable>

@end

CBATT请求+Requestable.m

#import "CBATTRequest+Requestable.h"

@implementation CBATTRequest (Requestable)

 - (NSString *)getCentralUUID {
    return self.central.identifier.UUIDString;
}

- (NSString *)getCharacteristicUUID {
    return self.characteristic.UUID.UUIDString;
}

- (NSData*)getData {
    return self.value;
}

- (void)setData:(NSData *) data {
    self.value = data;
}


@end

然后我在任何我想使用的地方导入类别。

经过长时间的研究和测试(感谢 Rob Napier),我找到了错误的根源。

我的项目由库和可执行目标组成。在库中,我定义了我的类别并在内部使用了它。问题是,当涉及到可执行文件的链接时,我的类别的 o 文件没有链接。参见 this stack post for further details on problems with categories in static libraries

一种可能的解决方案是将 exe 目标的链接器标志设置为 -Objc。

但我不喜欢这个解决方案,因为库能否正常工作将取决于 exe。

所以我在使用它的 m 文件中包含了类别的实现。

如果有人有另一个(更好的)解决方案,我会很高兴看到它。否则我会关闭这个问题。