iOS笔记—id

//
//  main.m
//  id
//
//  Created by hhg on 15-6-2.
//  Copyright (c) 2015年 hhg. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Person.h"
#import "Dog.h"
#import "Cat.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {

        Person *p = [Person alloc];
        Dog *d = [Dog alloc];
        Cat *c = [Cat alloc];

        // id 是指针类型,可以指向任意对象,不需要强制装换,可以直接使用
        id myId; // 用id类型声明一个myID泛型指针变量
        myId = p; //
        [myId setName:@"张胜男"]; // myId指向p,调用setName是调用p的方法;
        NSLog(@"name : %@", [myId name]);

        myId = d;
        [myId setAge:3];
        NSLog(@"age:%li", [myId age]);

        myId = c;
        [myId setColor:@"白色"];
        NSLog(@"颜色:%@", [myId color]);

        // 问题:如何知道id类型指向指向对象是属于哪个类?
        // [对象 class] 返回类名;
        NSLog(@"%@", [p class]);
        NSLog(@"%@", [d class]);
        NSLog(@"%@", [c class]);
        NSLog(@"%@", [myId class]);

    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/csdn_hhg/article/details/80460751