问题描述
我想用objective-c写一个返回块和链接调用的属性,但是如何返回instancetype?
@interface Person : NSObject
@property (nonatomic,weak,readonly) instancetype (^age)(int age);
@property (nonatomic,readonly) instancetype (^name)(Nsstring *name);
@end
我想要Person.new.age(10).name(@"Tom"),但是编译时instancetype是错误的
所以我这里必须把instancetype改成Person *
,但是如果我写了一个Person的子类,我就得再写一次:
@interface GoodPerson : NSObject
@property (nonatomic,readonly) GoodPerson * (^age)(int age);
@property (nonatomic,readonly) GoodPerson * (^name)(Nsstring *name);
@end
那么这里如何使用instancetype?
解决方法
你不能。 instancetype
不是有效的块返回类型。
使用 instancetype 关键字作为方法的返回类型,这些方法返回调用它们的类(或该类的子类)的实例。这些方法包括 alloc、init 和类工厂方法。
匿名块不满足这些条件。