ios - 在 iOS 中初始化泛型参数

标签 ios objective-c generics

我想用默认初始化器创建通用属性的对象。我知道这可以通过在 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/

相关文章:

c# - 通用直通接口(interface)。这可能吗?

ios - UIView 仅在一个 View Controller 中设置动画

ios - 使用低分辨率使用 AVCaptureVideoDataOutput 将 120/240 fps 捕获到帧缓冲区

swift - 如何正确创建自定义空纹理?

ios - 正则表达式卡在 iPhone 中用于电子邮件验证

c# - 如何在 C# 中调用带有泛型参数的泛型方法?

iOS NSTimeInterval 日期错误

ios - 当我使用 Afnetworking 从 Json 加载 url 图像时显示/隐藏事件指示器

objective-c - 如何将附加参数传递给 ASIHTTPRequest didFinishSelector 选择器

java - 未经检查的compareTo调用