Objective-C 块返回实例类型

问题描述

我想用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 不是有效的块返回类型。

来自https://developer.apple.com/library/archive/releasenotes/ObjectiveC/ModernizationObjC/AdoptingModernObjective-C/AdoptingModernObjective-C.html

使用 instancetype 关键字作为方法的返回类型,这些方法返回调用它们的类(或该类的子类)的实例。这些方法包括 alloc、init 和类工厂方法。

匿名块不满足这些条件。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...