Objective-C中的 id, isa,和 instancetype

本文详细解析Objective-C中的id、isa和instancetype。id是通用对象类型,用于动态类型和绑定;isa指向对象所属的类,涉及到类与元类的概念;instancetype确保初始化方法返回类型与接收者相同,有助于编译器进行类型检查。
摘要由CSDN通过智能技术生成

(1)id在动态类型的应用

在Objective-C Runtime Reference中,对id是这么定义和声明的:

id
A pointer to an instance of a class.
Declaration
typedef struct objc_object *id;

从定义来看,id是一个指向某个类的实例的指针。从声明来看,id是一个类型的别名,这个类型是“struct objc_object *”,也就是代表了指向一个objc_object结构体的指针。
id是一种通用的对象类型,可以用来存储任何类型的对象。也可以理解为“万能指针”。下面是《Programming in Objective-C》对id的作用的描述:

“That is, id can be used for storing objects that belong to any class. That real power of this data type is exploited when it’s used this way to store different types of objects in a variable during the execution of a program”

也就是,id可用于动态类型(dynamic typing)和动态绑定(dynamic binding)。例子如下:

//  Animal.h
#import <Foundation/Foundation.h>
@interface Animal : NSObject
-(void)eat;
@end

//  Animal.m
#import "Animal.h"
@implementation Animal
-(void)eat{
    NSLog(@"animal eat!");
}
@end

//  Person.h
#import "Animal.h"
@interface Person : Animal   //  Person类继承了Animal
@end

//  Person.m
#import "Person.h"
-(void)eat{
    NSLog(@"person eat!");   //  重写了Animal类中的eat方法
}
@end
//  main.m
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        id anInstance;       //此时 anInstance 对象为 id类型

        Animal *animal = [[Animal alloc] init];
        Person *person = [[Person alloc] init];

        anInstance = animal; //此时 anInstance 对象存储了 Ani
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值