- instancetype不可以跟id那样,作为参数进行传递,只可以作为方法的返回值
- 当一个类返回相同类的实例时可以使用instancetype
- 不在描述
3、代码反馈
Person.h
Person.m
Man.h
Man.m
调用执行过程如下:
main.m
在13行会有编译器提示,如下:

Person.h
点击(此处)折叠或打开
-
#import <Foundation/Foundation.h>
-
-
@interface Person : NSObject
-
-
+ (instancetype)personInstancetype;
-
+ (id)personID;
-
-
- (void)does;
- @end
点击(此处)折叠或打开
-
#import "Person.h"
-
-
@implementation Person
-
-
+ (instancetype)personInstancetype
-
{
-
return [[self alloc] init];
-
}
-
+ (id)personID
-
{
-
return [[self alloc] init];
-
}
-
- (void)does
-
{
-
NSLog(@"person does");
-
}
- @end
Man.h
点击(此处)折叠或打开
-
#import "Person.h"
-
-
@interface Man : Person
-
-
- (void)doIt;
- @end
Man.m
点击(此处)折叠或打开
-
#import "Man.h"
-
-
@implementation Man
-
-
- (void)doIt
-
{
-
NSLog(@"man do it ");
-
}
- @end
调用执行过程如下:
main.m
点击(此处)折叠或打开
-
#import <UIKit/UIKit.h>
-
-
#import "AppDelegate.h"
-
#import "Person.h"
-
#import "Man.h"
-
-
int main(int argc, char *argv[])
-
{
-
@autoreleasepool {
-
[[Person personID] does];
-
[[Person personID] doIt];
-
-
[[Person personInstancetype] doIt];
-
[[Person personInstancetype] does];
-
-
[[Man personInstancetype] doIt];
-
[[Man personInstancetype] does];
-
-
[[Man personID] does];
-
[[Man personID] doIt];
-
-
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
-
}
- }
点击(此处)折叠或打开
- /Users/...../Demo/Demo/main.m:21:38: No visible @interface for 'Person' declares the selector 'doIt'
