2011年8月14日 星期日

Xcode 學習筆記(三)iphone Application Developer(2009~2010 winter) 之一

3.Custom Classes,Object Lifecycle,Autorelease, Objective-C Properties (January 12,2010)




Time Line=04:20 Custom Classes
這篇主要是再講解如何建立一個新的class
名為person 的class
且繼承 NSObject class
規劃他的屬性
有名字,年紀,是否可以去投票
另外可以執行的動作為 去投票!


在Objective C 中主要的檔案格式分別為 header file(public) 跟 implementation file(private)
先從.h (副檔名) 講起
這是屬於 header file
內容格式如下
@interface [class name] : [superclass name] 
 @end
 所以這邊我們寫成
@interface person : NSObject 

另外因為NSObject是從Foundation 裡面取得
所以要加上
#import <Foundation/Foundation.h> 放在第一行
所以又會變成是

#import <Foundation/Foundation.h> 
@interface person : NSObject  
 @end

在來是放上名字跟年紀
名字是字串,年紀就是數字

#import <Foundation/Foundation.h> 


@interface person : NSObject 
//instance variables 
NSString *name;
int age; 
 }
 @end

在來是對name 跟 age方法的描述 以及可以法定投票跟投票的行為
// method declarations
- (NSString *)name;
- (void)setName:(NSString *)value;


- (int)age;
- (void)setAge:(int)age;


- (BOOL)canLegallyVote;
- (void)castBallot;


為什麼要在header file 加上這些呢
是因為header file 是class 的架構~
所以這邊需要清楚的寫好 變數 跟 方法

設定好header file後
再來換implementation file

講義裡面提到
我們在implementation file 裡面會包含 setter / getter 的方法
另外還有之前定義在header file的方法(cast ballot)


首先要先關聯header file 所以#import Person.h

#import "Person.h"


再來是 @implementation 加上 class name (後面要@end 結尾)


#import "Person.h"
@implementation Person




@end


(在objective c 裡面的@implementation 是專門定義類別方法的地方 the method of class)



#import "Person.h"
@implementation Person

// setter
- (int)age 
{
return age;
}



//getter

- (void)setAge:(int)value 
{
age = value;
}



//... and other methods
@end




再來提到在imlpement中 要呼叫內部的method 
要利用self 這個關鍵字


self 這個字 在Java 跟 C++ 中使用 "this" 是一樣的意思
(我想如果學過 Java 的人 應該就會有豁然開朗的感覺~)
甚至也可以使用 super 來呼叫 superclass


下面的範例就是使用 super 呼叫 dosomething 這個方法 並且 override 
- (void)doSomething {
// Call superclass implementation first
[super doSomething];
// Then do our custom behavior
int foo = bar;
// ...



==================================================
Time = 14:08

這邊學生發問了一個問題
提到 如果是多重繼承 (nested superclasses)
super 所呼叫的 method 會是哪一個
老師有舉例說明是
最頂層的是 NSObject  
下面有個A class 繼承 了NSObject
再來B class 繼承了 A class
用 super 呼叫 某個 method 的時候
她會先看 B class 有沒有 這個method
如果沒有 就會再往上看A class 有沒有method

沒有留言: