【Objective-C学习】id类型的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/glw0223/article/details/89489054

id :万能指针

  • 能够指向任何OC对象
  • id自带*。

id用法:

1.作为参数
2.作为成员变量

例如:
main.m

#import <Foundation/Foundation.h>
#import "Cat.h"
#import "Animal.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Animal *cat = [Cat new];
        [(Cat *)cat jump];

        NSObject *obj=[Cat new];
        [(Cat*)obj jump];

        //编译器对NSObject做类型检测,但是不对id做类型检测
        //所以id不用强制类型转换也可以运行成功,编译也报警告。
        id c=[Cat new];
        [c jump];
    }
    return 0;
}

参考:https://blog.csdn.net/glw0223/article/details/89480783

猜你喜欢

转载自blog.csdn.net/glw0223/article/details/89489054