我想用默认初始化器创建通用属性的对象。我知道这可以通过在 MyProtocol 中添加一个 init 方法来快速实现。有什么办法可以在 objective-c 中实现此功能
界面
@interface CustomClass<__covariant T:id<MyProtocol>> : NSObject
@property(nonatomic) T result;
-(void) update;
@end
实现
#import "CustomClass.h"
@implementation CustomClass
-(void) update
{
//self.result = initialize result here
[self.result myMethod];
}
@end
最佳答案
Objective-C 是后期绑定(bind)和动态类型。您既不需要模板(哎呀,他们称之为泛型),也不需要编译器绑定(bind)到它。只需使用 id
。
@interface CustomClass : NSObject
@property(nonatomic) id result;
-(void) update;
@end
-(void) update
{
//self.result = initialize result here
[self.result myMethod];
}
如果你出于任何原因想要对类型进行约束,只需使用协议(protocol):
@protocol CustomProtocol
- (void)myMethod;
@end
@interface CustomClass : NSObject
@property(nonatomic) id<MyProtocol> result;
-(void) update;
@end
-(void) update
{
//self.result = initialize result here
[self.result myMethod];
}
在评论中讨论主题后:
如果你想实例化一个泛型类型,你不需要在编译时这样做,而只是在运行时将类型传递给初始化程序。
代替……:
var concrete = CustomClass<Concrete>()
……你写:
CustomClass *concrete = [[CustomClass alloc] initForType:[Concrete class]];
我个人更喜欢新的分配器,但这是另一个讨论。您也可以将类型名称作为字符串传递。我个人也不喜欢那样。 :-)
初始化器看起来像这样:
- (instancetype)initForType:(Class)type
{
if( (self = [super init] )
{
self.result = [type new];
}
return self;
}
关于ios - 在 iOS 中初始化泛型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37907903/