OC面向對象五構造方法

id:萬能指針,已經帶*

typedef struct objc object{

Class isa;

} *id;


Person *p = [Person new];
NSObject * = [Person new];//id==NSObject *
id d=[Person new];//能操作任何OC對象
[d setAge:10];

@property id obj;//說明obj是任意類型
[d setObj:@"asdfa"];

  

構造方法:用來初始化對象的方法,是對象方法 -開頭

重寫構造方法目的:爲了讓對象創建出來,成員變量就會有一些固定的值

/*注意點:

先調用父類的構造方法([super init])

再進行子類內部成員變量的初始化

*/

Person *p = [Person new];//+ (id)new;

//先分配存儲空間+alloc,再初始化-init,初始值是0

Person *p2=[[Person alloc] init];//以後開發都這麼寫


若想改變init初始化爲自定義的值,就要重寫- init方法

- (id)init
{
	//1.一定要調用回super的init方法:初始化父類中聲明的一些成員變量和其他屬性
	self = [super init];  //返回當前對象,由於涉及到運行時,所以需要再次確定
	if (self !=nil)
	{//2.初始化成功
		_age=10;
	}
	return self;//3.返回一個已經初始化完畢的對象
}


 精簡:

- (id)init
{
	if(self = [super init])
	{
		_age=10;
	}
	return self;
}

自定義構造方法的規範

1.一定是對象方法,一定以  -   開頭

2.返回值一般是id類型

3.方法名一般以init開頭

- (id)initWithName:(NSString *)name andAge:(int)age;
- (id)initWithName:(NSString *)name andAge:(int)age
{
	if(self=[super init])
	{
		_name=name;
		_age=age;
	}
	return self;
}
Person *p = [[Person alloc] initWithName:@"Rose" andAge:20];

父類屬性(成員變量)交給父類去處理,子類屬性交給子類自己處理

Student 繼承Person 自定義構造方法

- (id)initWithName:(NSString *)name andAge:(int)age andNo:(int)no
{
//由於子類無法改變父類的成員變量,無法使用_name=name;可以用self.name=name;或[self setName:name];代替之。
//另一個好處就是,父類的name值改了,不需要子類再去改。
   if(self = [super initWithName:name andAge:age])//一般通過super父類的方法實現我們自定義構造方法初始化指定的值
    {
     _no=no;
     }
   return self;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章