目的:创建Person类,Student子类继承Person,创建一个Person类的person类方法,哪个类调用就创建自己类的对象并自动加入到释放池。重写dealloc方法来体现出自动释放池程序段结束后已各自自动释放。
main.m
- #import <Foundation/Foundation.h>
- #import "Person.h"
- #import "Student.h"
- int main(int argc, const char * argv[]) {
- @autoreleasepool {
- Person *p=[Person person];
- p.name=@"Human";
- [p run];
- Student *stu=[Student person]; //动态类型,直到程序执行时才知道stu是什么类型
- stu.name=@"Little boy";
- [stu run];
-
- /* 存在问题:
- 当写入语句
- NSString *str=[Student person];
- 的时候,能体现出person类方法的返回值类型用instancetype而不用id的区别,用instancetype能检查出返回类型为student类型而目标类型为Nsstring *类型的不匹配,系统会提出警告,而用id不能检查到。
- */
- }
- return 0;
- }
复制代码
Person.h
- #import <Foundation/Foundation.h>
- @interface Person : NSObject
- @property(nonatomic,copy)NSString *name;
- -(void)run;
- +(instancetype)person;
- @end
复制代码
Person.m
- #import "Person.h"
- @implementation Person
- -(void)dealloc{
- NSLog(@"Person:%@----dealloc!",self.name);
- [super dealloc];
- }
- +(instancetype)person{
- return [[[self alloc]init]autorelease];//为了Student *stu=[Student person];创建的不是Person类的对象,而是Student类的对象,这样可以调用Student类自己的run方法。
- }
- -(void)run{
- NSLog(@"Person:%@ is running!",self.name);
- }
- @end
复制代码
Student.h
- #import "Person.h"
- @interface Student : Person
- -(void)run;
- @end
复制代码
Student.m
- #import "Student.h"
- @implementation Student
- -(void)run{
- NSLog(@"Student:%@ is running!",self.name);
- }
- -(void)dealloc{
- NSLog(@"Student:%@----dealloc!",self.name);
- [super dealloc];//调用父类的dealloc方法
- }
- @end
复制代码 |
|