我可以在类扩展中更改属性的类型吗?

时间:2018-01-17 17:18:16

标签: objective-c clang

我希望在公共标头中公开具有泛型类型的属性,然后在私有标头中将其类型更改为更具体的类型。我使用的是Clang,但虽然我能够改变其读/写属性,但它并不接受不同的类型。到目前为止,这是我尝试过的:

普通客户端会导入BKSystem.h

@interface BKSystem : NSObject

@property(nonatomic, readonly) id<XYZWorker> worker;

@end

虽然测试客户端可以通过导入BKSystem+Testing.h来访问内部:

#import "BKSystem.h"

@interface BKConfigurableWorker : NSObject<XYZWorker>

@property(nonatomic) BKConfiguration *config;

@end

#pragma mark -

@interface BKSystem ()

// Attempts to change worker to be writable and with a more specific type.
@property(nonatomic, readwrite) BKConfigurableWorker *worker;

@end

但在测试客户端上,这就是我得到的:

#import "BKSystem+Testing.h"

BKSystem *system = [[BKSystem alloc] init];

// I am able to write to this property.
system.worker = [[BKConfigurableWorker alloc] init];

// ERROR: Property 'config' not found on object of type 'id<XYZWorker>'
system.worker.config = [[BKConfiguration alloc] init];

1 个答案:

答案 0 :(得分:0)

要完成您尝试做的事情,我会使用BKWorker作为子类而不是协议。请参阅下面的示例头文件:

@interface BKConfiguration : NSObject

@end

@interface BKWorker : NSObject

@property (nonatomic, strong, readonly) BKConfiguration *config;

@end


@interface BKConfigurableWorker : BKWorker

@property (nonatomic, strong, readwrite) BKConfiguration *config;

@end

请注意,在可配置工作器中再次声明了相同的属性,但是readwrite而不是readonly

在实现中使用时会产生以下结果:

example

注意可配置工作者如何写入,但标准工作者不能写入。

希望这有帮助。

相关问题