数据类型之id类型
id数据类型可以存储任何类型的对象。在概念上类似于Java中的Object类,可以被转换为任何数据类型。在内部处理中,id是一个指向任何一个继承了Object或者NSObject类的对象,在使用时不用加星号。
Student.h
#import <Foundation/Foundation.h> @interface Student : NSObject { int sid; //学号 NSString *name; //姓名 } @property int sid; @property (nonatomic,retain)NSString *name; -(void)print; //声明一个名为print的实例方法 -(void)setSid:(int)sid andName:(NSString*)name; @end
Student.m
#import "Student.h" @implementation Student @synthesize sid,name; -(void)print { NSLog(@"My number is %i,and My name is %@",sid,name); } -(void)setSid:(int)sid1 andName:(NSString*)name1 { self.sid=sid1; self.name=name1; } @end
Member.h
#import <Foundation/Foundation.h> @interface Member : NSObject { int age; NSString *name; } @property(nonatomic,retain)NSString *name; @property int age; -(void)print; -(void)setName:(NSString *)name1 andAge:(int)age1; @end
Member.m
#import "Member.h" @implementation Member @synthesize age,name; -(void)print{ NSLog(@"Myname is %@,Myage is %i",name,age); } -(void)setName:(NSString *)name1 andAge:(int)age1{ self.age=age1; self.name=name1; } @end
main.m
#import <UIKit/UIKit.h> #import "AppDelegate.h" #import "Member.h" #import "Student.h" int main(int argc, char * argv[]) { @autoreleasepool { NSLog(@"My First App is Run!"); //为什么加了这句以后下面的print就打不出来了? Member *member1=[[Member alloc]init]; [member1 setName:@"zhangsan" andAge:24]; id data; //定义了一个id类型的变量data data=member1; [data print]; Student *student1=[[Student alloc]init]; [student1 setSid:9527 andName:@"huaan"]; data=student1; [data print]; } return 0; }