1. 程式人生 > >變量,構造方法

變量,構造方法

定義 失敗 self atom type pro sel turn string

一、property屬性

在類中定義成員變量時,使用

1 @interface Person: NSObject{
2 
3     NSString *name;
4 
5 }
6 @end

時,需自己定義getter和setter方法,比較麻煩,而使用property時,系統自動定義了getter和setter方法,比較簡便

 1 #import <Foundation/Foundation.h>
 2 #import "Car.h"
 3 
 4 @interface Person : NSObject
 5 
 6 @property (nonatomic, strong) NSString *name;
7 @property (nonatomic, strong) Car *che; 8 9 - (void)showCar; 10 11 @end
 1 #import <Foundation/Foundation.h>
 2 
 3 typedef enum : NSUInteger {
 4     kCarTypeA3,//0
 5     kCarTypeA4,//1
 6     kCarTypeA5//2
 7 } kCarType;
 8 
 9 @interface Car : NSObject
10 
11 @property (nonatomic, strong) NSString *color;
12 @property (nonatomic, strong) NSString *brand; 13 @property (nonatomic, assign) kCarType type; 14 15 @end

在主函數中調用:

 1 #import <Foundation/Foundation.h>
 2 #import "Car.h"
 3 #import "Person.h"
 4 
 5 int main(int argc, const char * argv[]) {
 6     @autoreleasepool {
 7         Car *cc = [Car new
]; 8 [cc setColor:@"褐色"]; 9 cc.brand = @"大眾"; 10 cc.type = kCarTypeA3; 11 12 Person *pp = [Person new]; 13 pp.name = @"jack"; 14 pp.che = cc; 15 16 [pp showCar]; 17 18 } 19 return 0; 20 }

總結以下幾點:

1.set方法:[cc setColor:@"red"]; 或者cc.color = @"red";

2.get方法:[cc name];或者cc.name;

3.點語法只能用於property屬性的變量

二、構造方法

1.概念:自定義初始化方法 init方法,在創建這個對象的同時 對這個對象進行初始化,initWith開頭,通常有3種返回類型 

- (id)

- (Car *)

- (instancetype)

2.用法舉例

 1 #import <Foundation/Foundation.h>
 2 
 3 typedef enum : NSUInteger {
 4     kCarTypeA3,//0
 5     kCarTypeA4,//1
 6     kCarTypeA5//2
 7 } kCarType;
 8 
 9 @interface Car : NSObject
10 
11 @property (nonatomic, strong) NSString *color;
12 @property (nonatomic, strong) NSString *brand;
13 @property (nonatomic, assign) kCarType type;
14 
15 - (instancetype)initWithColor:(NSString *)aColor
16                      andBrand:(NSString *)aBrand
17                       andType:(kCarType)aType;
18 
19 @end
 1 #import "Car.h"
 2 
 3 @implementation Car
 4 
 5 //重寫父類的init方法
 6 - (instancetype)init{
 7     //nil空 NULL指針為空
 8     //super 告訴編譯器從我的上一級去查找(父類)
 9     //self 如果初始化失敗 返回nil
10     self = [super init];
11     
12     if (self != nil) {
13         self.color = @"黑色";
14         self.brand = @"大眾";
15         self.type = kCarTypeA4;
16     }
17     
18     return self;
19 }
20 
21 - (instancetype)initWithColor:(NSString *)aColor
22                      andBrand:(NSString *)aBrand
23                       andType:(kCarType)aType{
24     self = [super init];
25     
26     if(self != nil){
27         self.color = aColor;
28         self.brand = aBrand;
29         self.type = aType;
30     }
31     return self;
32 }
33 @end

3.註意:

1??self = [super init];是對對象進行初始化,如果失敗,則返回nil代表沒有內存,成功則返回對象,NSString *str = nil; str沒有內存,不存在

2??一般自己重寫構造方法,即用initWith,可隨意改變初始值

變量,構造方法