Objective-C class 类型 "self" 的方法局部变量

Objective-C class method local variables of type "self"

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

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

这是有效的,因为 "self" 在这种情况下指的是 class 而不是从 class 蓝图构建的对象。

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

typeof(self) someStrongSelf = self;

这允许 self 的类型是动态的,并且无论 class.

是什么,都可以将代码复制粘贴到任何需要的地方

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

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

    return instance;
}

这是行不通的,因为 self 是一个 class,而 typeof(class) 只是一个 Class,但是局部变量是否有某种机制等同于instancetype 这将使我具有与 typeof(instance) 相同的灵活性?例如:

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

    return instance;
}

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

我明白你在找什么,但没有 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 实例。