【问题标题】:Objective-C class method local variables of type "self"“self”类型的 Objective-C 类方法局部变量
【发布时间】:2017-03-21 18:26:37
【问题描述】:

我们都熟悉以下用于实例化类实例的模式:

+ (instancetype)createInstance {
    return [[self alloc] init];
}

之所以可行,是因为在这种情况下,“self”指的是类,而不是从类蓝图构建的对象。

我们也知道这个声明,最常用于避免保留循环:

typeof(self) someStrongSelf = self;

这允许self 的类型是动态的,并且无论类如何,都可以将代码复制粘贴到任何需要的地方。

我的问题涉及从类方法实例化时结合上述两种模式:

+ (instancetype)createInstance:(MyObject*)dependency {
    typeof(self) instance = [[self alloc] init];
    instance.dependency = dependency;

    return instance;
}

这是行不通的,因为self 是一个类,而typeof(class) 只是一个Class,但是是否有一些局部变量等效于instancetype 的机制可以让我获得与typeof 相同的灵活性(实例)?例如:

+ (instancetype)createInstance:(MyObject*)dependency {
    instanceof(self) instance = [[self alloc] init]; //desired keyword
    instance.dependency = dependency;

    return instance;
}

如果我真的想要这个形式化,我知道一个替代方案是定义一个与上述基本相同的协议,但我很好奇 Objective-C 是否允许开箱即用的所需声明样式。

【问题讨论】:

  • 我同意@Rob。不知道你为什么要让它如此通用。 TheClass *instance = [[TheClass alloc] init]; instance.dependency = dependency;
  • 我承认我的问题没有太多实际原因。我只是发现自己经常强烈地打电话给[[self alloc] init],以至于我很好奇我是否忽略了一个关键字。但我想这会出现在任何与 Objective-C 相关的 SO 问题中......

标签: objective-c dynamic-typing


【解决方案1】:

我了解您要查找的内容,但没有 instanceof(self) 模式。以下实现了您想要的,但诚然没有typeof(self) 模式的优雅:

@interface Foo: NSObject
@property (nonatomic, copy) NSString *string;
@end

@implementation Foo
+ (instancetype)fooWithString:(NSString *)string {
    Foo *foo = [[self alloc] init];
    foo.string = string;
    return foo;
}
@end

@interface Foobar: Foo
// perhaps some more properties here
@end

@implementation Foobar
// and perhaps some more methods here
@end

这个实现展示了便捷方法仍然允许子类化。即,您可以这样做:

Foobar *foobar = [Foobar fooWithString:@"baz"];

结果对象将是一个Foobar 实例。

【讨论】:

  • 是的,这通常是我遵循的模式。令人失望的是,从班级的角度来看,self 没有互补关键字,但你能做什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多