main.m
1 //
2 // main.m
3 // 便利構造器與autorelease
4 //
5 // Created by sixleaves on 15/5/10.
6 // Copyright (c) 2015年 itcast. All rights reserved.
7 //
8
9 #import <Foundation/Foundation.h>
10 #import "Person.h"
11 #import "GoodPerson.h"
12 int main(int argc, const char * argv[]) {
13 @autoreleasepool {
14
15
16 Person *p1 = [Person person];
17 p1.age = 100;
18
19 GoodPerson * p2 = [GoodPerson personWithAge: 150];
20
21 // p2實際上指向的是Person
22 p2.money = 300;
23
24 //NSLog(@"test");
25
26 /*
27 代碼分析:
28 GoodPerson類調用了personWithAge,所以根據誰調用我,self就指向誰這個原則。
29 self指向GoodPerson類。GoodPerson中沒有這個方法,就只能到父類中找,到父類
30 中找到了又調用[self person],GoodPerson中又沒有這個方法,于是又找父類,找到后,創建是已經autorelease的Person對象。而不是GoodPerson對象。此時我們只需改掉person方法中寫死的[Person alloc]換成self alloc就可以,為什么呢。因為self此時指向的是子類,所以創建出來的就是子類。
31
32 對于GoodPerson,并沒有重寫自己的dealloc方法,所以調用的時候,在GoodPerson中找不到,就去其父類Person中找,找到了后,調用了Person得dealloc方法。
33 */
34
35
36 }
37 return 0;
38 }
39
40 /*
41 便利構造器的概念:
42 1.開發中,我們經常會提供一些類方法,快速創建一個已經autorelease的對象。(便利構造器\便利構造方法)
43 便利構造器與self:
44 1.在便利構造器中,盡量使用self代替類名。(或者self class).這能讓子類調用時候創造出來的就是子類對象。
45 */
46
Person.h
1 //
2 // Person.h
3 // 便利構造器與autorelease
4 //
5 // Created by sixleaves on 15/5/10.
6 // Copyright (c) 2015年 itcast. All rights reserved.
7 //
8
9 #import <Foundation/Foundation.h>
10
11 @interface Person : NSObject
12
13 @property (nonatomic, assign) int age;
14
15 // 遍歷構造器
16
17 + (id)person;
18
19 + (id)personWithAge:(int)age;
20
21 @end
22
Person.m
1 //
2 // Person.m
3 // 便利構造器與autorelease
4 //
5 // Created by sixleaves on 15/5/10.
6 // Copyright (c) 2015年 itcast. All rights reserved.
7 //
8
9 #import "Person.h"
10
11 @implementation Person
12
13 // 便利構造器與autorelease
14 /*
15 便利構造器的規范:
16 1.必須是類方法,
17 2.返回類型是id
18 3.必須以類名With開頭(帶參數一般還要有With),區別之一是便利構造器必須是小寫駱駝峰,而類名是大寫的。
19
20 */
21
22 + (id)person
23 {
24 // return [[[Person alloc] init] autorelease]會導致子類調用personWithAge、person創建的都是已經autorelease的Person對象
25 // 而不是想要的子類對象。換成self就可解決,具體分析看代碼分析。
26 return [[[self alloc] init] autorelease];
27 }
28
29 + (id)personWithAge:(int)age
30 {
31 Person *p = [self person];
32 p.age = age;
33 return p;
34 }
35
36 - (void)dealloc
37 {
38 NSLog(@"%d歲的對象被銷毀了~~~", _age);
39 [super dealloc];
40 }
41
42 @end
43
GoodPerson.h
1 //
2 // GoodPerson.h
3 // 便利構造器與autorelease
4 //
5 // Created by sixleaves on 15/5/10.
6 // Copyright (c) 2015年 itcast. All rights reserved.
7 //
8
9 #import "Person.h"
10
11 @interface GoodPerson : Person
12
13 @property (nonatomic, assign) int money;
14
15 @end
16
GoodPerson.m
1 // 2 // GoodPerson.m
3 // 便利構造器與autorelease
4 //
5 // Created by sixleaves on 15/5/10.
6 // Copyright (c) 2015年 itcast. All rights reserved.
7 //
8
9 #import "GoodPerson.h"
10
11 @implementation GoodPerson
12
13 - (void)dealloc
14 {
15
16 NSLog(@"GoodPerson-dealloc");
17 [super dealloc];
18 }
19
20 @end
21