2010年11月30日 星期二

Xcode 上手












感謝大家看到最後,不好意思是都是用圖上傳,因為我找不到當初screen shot 的圖了,所以整個用圖片上傳,讓大家眼睛吃力了。這是我的書的一部分,正在努力寫書中,希望明年一月會出版,請大家拭目以待,如果有什麼錯誤的地方,也請多多指教。


2010年11月29日 星期一

Objecitive-C Compiler for Windows ? あるよ!

雖然筆者是多年的 mac user ,但因為朋友大多數還是 windows user 然後想學 objective-c 的人也不少,為了幫助朋友,之前筆者也是花了一些時間在找Windows 上面的 Objective-C 的 Compiler ,就只有發現
GNUStep : http://www.gnustep.org/information/openstep.html
這個還可以 run 出個 Hello World 。
但是從安裝到 run 出個 Hello World 也花了很多氣力,安裝完之後,整個寫 Code 精神都沒了。orz

最近竟然發現到這樣的一個 Compiler
OSCompiler : http://code.google.com/p/oscompiler/
這是寫在 .net 之下的 Objective-C Compiler
只要安裝 .net 4 以上就可以跑了
安裝 .net 4 的環境之後可以解開
OSCv0.1.4.zip
然後把
Exmp1.m Exmp2.m 都放到被解開的資料夾裡
馬上就打開 Console 來測試一下是不是可用?呵
打上 osc.exe Exmp1.m 如圖所示
 沒有任何錯誤,會產生  Exmp1.exe
然後接著打 Exmp1.exe 如圖
此時 Hello world ! 就跑出來了。
這麼簡單,真是感動啊 !!!!!
接下來看一下 Exmp1.m 的內容長這樣
#import <Foundation/Foundation.h>
                                            
@interface Main : NSObject { }
@end

@implementation Main
    +(void)main {
    NSLog(@"Hello world!");
    }
@end
一開始也是 import Foundation 和我們熟知的一樣
再來就比較不一樣了,main function 是寫在
  +(void)main {
    NSLog(@"Hello world!");
    }
所以我們記得就這樣寫,把 code 寫在 +(void)main 就沒錯了。
最後,雖然直接用 Command Line 下指令也是滿方便的
筆者秉持著熱心助人的精神,試了幾個免費的Editor ,在這介紹一個好用的叫 Crimson Editor
在這邊下載
Crimson Editor : http://www.crimsoneditor.com/
好用的地方除了有一些顏色之外,還有方便自訂的Tool
按照下面一步一步的做法,就可以用 Ctrl + 1 執行 Compile 指令
首先在 Tools -> Conf. User Tools
然後會看到

設定就照著圖選,然後在 Command 那個地方選擇 osc.exe
之後開啟 Exmp1.m 這個檔,接著按下 Ctrl 1 就會看到底下有 Output 說明產生 Exmp1.exe 了
接著按下 F10 就會呼叫起 Console

再打上 Exmp1.exe 就會看到執行結果了。

有空的大家可以多幫忙測一下這個 compiler 的完整度,如果有 windows user 想學 objective-c 的正好也可以試試。底下我會列一些我測試過的結果

#import 自定的.h  -  失敗
自定 Class 寫在 + main 同一個檔案 - 成功
找不到 retainCount 看來記憶體管理應該是 - 失敗
property  -  成功
簡單 protocol - 成功  
單行 protocol 宣告 : @protocol someName; -  失敗
id<protocolName> - 失敗

2010年11月23日 星期二

Protocol & Delegate

Protocol

在Objective-C 中protocol 就是一個很多 method 的宣告集合的地方,感覺上和interface 有點像而和interface的差別在於protocol 裡面不會有變數的宣告。我們直接來看一個例子。
@protocol Omniprinter

-(void) printInt:(int ) intVar;
-(void) printObj:(NSString *) obj;

@end
這個例子就是,我們宣告了一個protocol 叫 Omniprinter 前面需要加上關鍵字@protocol,這個protocol 裡面就只有 printInt: 和 printObj: 這兩個 method。Protocol 就這樣簡單地宣告完成了。如果是要接受或叫遵循這個 protocol 的 class就要在@interface這樣寫。
@interface Hello: NSObject<Omniprinter>{
}
@end
這個就代表 Hello 這個 Class 有採用 Omniprinter 所定義的 method 。如果一次要採用很多個 protocol 就用 , 逗點分開每個 protocol 的名字,比如。
@interface Hello: NSObject<Omniprinter, protocol1, protocol2 >
當我們寫在 interface 說要採用某個 protocol 的時候我們就有可能會在 implementation 這樣寫。
@implementation Hello
-(void) printObj:(NSString *) obj{
    NSLog(@"%@", obj);
}
@end
就是把 protocol 所宣告的 method 實作在有採用這個 protocol 的 Class 的 implementation 的部分。在上面的例子筆者故意只寫一個 method 實作,是要來說明 protocol 裡的 method 還有分別的。比如剛剛的 protocol ,Omniprinter 我們加幾個關鍵字。
@protocol Omniprinter

@optional
-(void) printInt:(int ) intVar;
@required
-(void) printObj:(NSString *) obj;

@end
看名字就知道在@optional 之後的 method 是選擇要不要實作的,而在 @required 之後的 method 的是一定要實作的,如果什麼都沒有寫預設就是 @required 。如果不遵這樣的規則Xcode 會給警告。Protocol 本質上就是這樣簡單的一個機制,在 implementation 要實作在 interface 所採用的 protocol 的 method 。

型別裡的Protocol

接著要介紹的觀念是當Protocol 放到型別裡的時候是怎麼樣的情況,先來看這個例子。
id<Omniprinter> delegate ;
這樣子的寫法是代表說 delegate 這個變數,它可以是任意型別,但一定要遵循 Omniprinter 這個 protocol ,也就是說,delegate 的實體必需要實作 Omniprinter 所定義的@required 的  method 。如果我們限制 delegate 的型別呢?就會這樣寫。
Hello<Omniprinter> * delegate ;
這樣就代表 delegate 這個變數所存的實體必需是 Hello * 這個型別而且要有實作 Omniprinter 這個 protocol 裡面 @required 的 method 。

NSObject 與 <NSObject>

我們知道所有的自訂的Class 都要繼承自 NSObject 這個 Class ,而在 protocol 的世界裡也有一個叫 NSObject 的 protocol ,如果去查這個 protocol 所規範的 method 不外乎就是 init ,release ,retain 等等的在NSObject 有定義過的 method 。其實 NSObject 就是遵循了<NSObject> 而實作了重要的 method 。如果我們這樣寫。
@protocol Omniprinter<NSObject>
代表著這個 Omniprinter protocol 也採用了<NSObject> 這個 protocol 。那也就是說如果這樣寫。
id<Omniprinter> delegate ;
也就代表著 delegate 也要實作 <NSObject> 所宣告的 @required method。那是不是要寫很多程式?不用怕,還記得所有的我們自訂的或是系統提供的Class都繼承自 NSObject 這個 Class 嗎?自然也就有 <NSObject> 的實作了,只要我們照著規範做就可以省去很多事情。

委任 - Delegate

談到Protocol 就不得不談一個Design Pattern 叫做 Delegate  (委任),在 Objective-C 裡面經常用 Protocol 來完成 Delegate 所要做的事情。委任就是某 A 要完成一件事情,A 沒辦法自己獨力完成,而需要借用其他人,比如 B 的能力來完成。此時,A 就是委任者,B 就是受委任者。換成程式語言來說能力就是 method ,當 A 的能力不足的時候,就是 method 的功能不多,當 A 委任給 B 來做事的時候,就是利用 B 的 method 來完成事情。我們來看一個很簡單的例子。假設 B 是另一個 Class 。
@interface A {
    B * delegate;
}
@end

@implementation A
-(void) doSomething {
    [ delegate  actionOfB ];
}
@end
這個例子很簡子的只是在 doSomething 這個 method 裡呼叫 delegate 的 actionOfB 這個 method 。但其中隱含的概念是,A 這個 Class 借用 B 的能力 ( method ) 來完成 A 的 doSomething 這件事。delegate 這個變數的型別是 B * ,無論其在什麼時候給一個 B 的實體,在 A 的 method ,doSomething 裡被借用了能力( method ) 就是受了 A 的委任來完成事情。這就是一個很簡單委任的例子。接著我們來看看在 Objective-C 裡怎麼用委任這個概念。尤於要寫的內容太多,這個例子就分成幾個檔案。把 @interface 都放在 .h 檔,@implementation 都放在 .m  檔裡。
新增 MyWallet.h 以及 MyWallet.m 檔。
在 MyWallet.h 打上這樣的程式碼:
#import <Foundation/Foundation.h>

@protocol examMoney;
@interface MyWallet : NSObject {
    NSString * title;
    float money;
    id<examMoney> delegate;
}
-(void ) showTheMoney;
@property (assign) id<examMoney> delegate;
@property (retain) NSString * title;
@property (assign) float money;
@end

@protocol examMoney<NSObject>

-(void) getWallet:(MyWallet *) wallet withMoney:(float) money;

@end
在 MyWallet.h 裡我們把先寫了這樣的宣告 @protocol examMoney; 這列是要和 compiler 說 examMoney 這串字不是別的正是 protocol 。然後接著宣告 MyWallet 這個 Class 的 interface 的部分。也就是 @interface 到 @end ,這中間的程式碼。MyWallet 這個 Class 有三個實體變數 title , money 和 delegate ,分別都有各自的property 宣告。其中筆者要強調的當然就是 delegate 這個變數,其型別為 id<examMoney> 也就是就說這個變數所要存放的實體必需要實作 <examMoney> 這個 protocol ,雖然看到這列還不知道 protocol 內容長什麼樣,但是就語法來說,這樣就是合法的。再來看一下 delegate 的 property 的 attribute 為 assign ,還記得筆者說過,有 protocol 型別的 property ,其 attribute 要用 assign 就和 money 這個 primitive 型別的變數一樣要用 assign 。在這個例子 NSString * title 的 property attribute 筆者習慣用 retain 。再往下看程式碼,就看到了 <examMoney> 這個 protocol 的內容,真正需要實作的 method 叫什麼名字了。把這個檔案從頭看到尾就發現我們其實把 Class 的宣和 Protocol 的內容放在一起,而且,注意看 Protocol 的 method 第一個傳入的參數是什麼型別?就是這個 Class 的型別。這樣的寫法雖然是 MyWallet 要委任 <examMoney>   給別人完成,但看起來也很像是 MyWallet 把資料傳給另一個物件。所以也有人說這是一種在 Objective-C 裡面物件之間傳遞資料的方法。至於 showTheMoney 的用途在接下來會解說。
接著看 MyWallet.m 裡面要寫什麼。
#import "MyWallet.h"
@implementation MyWallet
@synthesize delegate, title, money;
-(void) showTheMoney {
    if ([delegate respondsToSelector:@selector(getWallet:withMoney:)]) {
        [delegate getWallet:self withMoney:money];
    }else {
        NSLog(@"Please implement getWallet:withMoney: ");
    }

}
@end
在這個檔案裡,除了把 property ,synthesize 之外,還有寫了 showTheMoney 的實作。showTheMoney 這個 method 實作的內容就是把 delegate 這個有實作 <examMoney> 的物件直接拿來用,也就是呼叫 @selector(getWallet:withMoney:) ,但是在此之前要先檢查一下 delegate 所存的物件是不是真的有實作 getWallet:withMoney: 於是先用 responseToSelector: 來判斷 delegate 是否有實作,否則就印出訊息在 Console。委任者寫完了,再來看看受委任者的寫法。再新增 OmniExamer.h 和 OmniExamer.m 兩個檔案。
OmniExamer.h 的內容會是
#import <Foundation/Foundation.h>
#import "MyWallet.h"

@interface OmniExamer : NSObject<examMoney> {

}

@end
OmniExamer 這個 Class 最主要的目的就是實作 <examMoney> 的 method ,一開始先 #import "MyWallet.h" 讓 OmniExamer 知道 <examMoney> 和 MyWallet 的存在。然後在 Class 最後寫 :NSObject<examMoney> 就是繼承 NSObject 而且遵循 <examMoney>  的規範,就這樣就可以了。
接著看 OmniExamer.m 的寫法。
#import "OmniExamer.h"

@implementation OmniExamer

-(void) getWallet:(MyWallet *) wallet withMoney:(float) money{
    NSLog(@"The wallet : %@ with Money %f ", wallet.title, money);
}
@end

一開始就是 import OmniExamer.h 然後就是重點,實作 <examMoney> 的 getWallet:withMoney: ,在這個例子就是把 money 印在 Console 而且因為第一個參數就是MyWallet 的物件,所以我們可以甚至可以把MyWallet 物件的property 拿來用,就好像這個列子一樣,在印 money 之前把 wallet.title 也印在 Console。
當我們這四個檔案就準備好了,就剩下在 main 測試了。main.m 請如下打字。


#import <Foundation/Foundation.h>
#import "OmniExamer.h"
int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    MyWallet * wallet = [MyWallet new];
    wallet.title = @"New Wallet";
    wallet.money = 500.0;
    OmniExamer * oe = [OmniExamer new];
    wallet.delegate = oe;
    [wallet showTheMoney];

    [pool drain];
    return 0;
}
一開始當然要先 import OmniExamer.h 這樣才可以知道 OmniExamer Class 而 OmniExamer.h 又有 import MyWallet.h 所以也可以知道 MyWallect Class 和 examMoney Protocol 。在 main function 裡就是產生 MyWallet 的實體放在 wallet 這個變數裡,然後設定 title 和 money ,再產生 OmniExamer 的實體放在 oe 。接者就是重點了,把 wallet.delegate = oe ; 這個程式就是表示 wallet.delegate 目前和 oe 指向相同的物件實體,也就是委任關系的成立,wallet 可以透過 delegate 來使用 oe 所實作 <examMoney> 的 method 。最後就是 [wallet showTheMoney]; 呼叫 showTheMoney ,還記得此 method 用了 delegate 來做事吧,執行到此 delegate 就有 oe 所指的物件實體,也就是 oe 在幫 wallet 做事了,而且 wallet 的資料也傳到 oe 上面。

2010年11月11日 星期四

iOS - Internationalization

這篇文章是和大家分享如何在不同的語言設定下,讀取不同的文字
首先呢就產生一個Project,這個例子叫LangTest
然後在這個Project 所在的Finder位置。(用Reveal in Finder)
手動新增所需要的語言資料夾,在這個例子我新增了四個
en.lproj
it.lproj
zh_tw.lproj
zh_cn.lproj
命名規則就是xx.lporj 至於 xx 是什麼要去查iso 639-1
然後回到xcode在Resource Group裡按右鍵新增File
選Mac OS -> Resource -> Strings File 命名為Localizable.strings
然後Location要選剛剛新增的某一個xx.lrpoj哦。

換句話說,每一個xx.lproj都要新增Localizable.strings。然後會看到Xcode裡自動排成

接下來就是在每個Localizable.strings都要貼上key=value的配對。
比如zh_tw 的就是寫 "Welcome" = "你好"; // Welcome就是Key, 你好就是value
在en 的就是 "Welcome" = "Welcome";
之後在任何地方使用 NSLocalizedString(@"Welcome", @"");
這樣就會回傳手機設定語言的值了。

這裡有Source Code : http://goo.gl/puvfW

2010年11月5日 星期五

Block

Apple 在C, Objective-C, C++加上Block這個延申用法。目前只有Mac 10.6 和iOS 4有支援。Block是由一堆可執行的程式組成,也可以稱做沒有名字的Function (Anonymous function)。如果是Mac 10.6 或 iOS 4.0 之前的平台可以利用 http://code.google.com/p/plblocks/ 這個project得以支援Block語法。
Apple有一個叫做GCD(Grand Central Dispach)的新功能,用在同步處理(concurrency)的環境下有更好的效率。Block語法產生的動機就是來自於GCD,用Block包好一個工作量交給GCD,GCD有一個宏觀的視野可以來分配CPU,GPU,Memory的來下最好的決定。

Block 簡介

Block其實行為和Function很像,最大的差別是在可以存取同一個Scope的變數值。
Block 實體會長成這樣
^(傳入參數列) {行為主體};

Block實體開頭是"^",接著是由小括號所包起來的參數列(比如 int a, int b, float c),行為的主體由大括號包起來,專有名詞叫做block literal。行為主體可以用return回傳值,型別會被compiler自動辦識出來。如果沒有參數列要這樣寫(void)。
看個列子
^(int a) {return a*a;};
這是代表Block會回傳輸入值的平方值(int a 就是參數列return a*a; 就是行為主體)。記得主體裡最後要加";"因為是敘述,而整個{}最後也要要加";"因為Block是個物件實體。
用法就是
int result = ^(int a) {return a*a;} (5);
很怪吧。後面小括號裡的5 會被當成a的輸入值然後經由Block輸出5*5 = 25指定給result這個變數。
有沒有簡單一點的方法不然每次都要寫這麼長?有。接下來要介紹一個叫Block Pointer的東西來簡化我們的寫法。
Block Pointer是這樣宣告的
回傳值 (^名字) (參數列);

直接來看一個列子
int (^square) (int); 
// 有一個叫squareBlock Pointer,其所指向的Block是有一個int 輸入和 int 輸出

square = ^(int a ) {return a*a ;}; // 將剛剛Block 實體指定給 square

使用Block Pointer的例子
int result = square(5); // 感覺上不就是funtion的用法嗎?
也可以把Block Pointer當成參數傳給一個function,比如說
void myFuction( int (^mySquare) (int) ); // function 的宣告,
傳入一個有一個int輸入和int輸出的Block 型別的參數
呼叫這個myFunction的時候就是這樣呼叫
int (^mySqaure) (int) = ^(int a) {return a*a;};
// 先給好一個有實體的block pointer叫mySquare

myFunction( mySqaure ) ; //把mySquare這個block pointer給myFunction這個function
或是不用block pointer 直接給一個block 實體,就這樣寫
 myFunction(  ^(int a) {return a*a} ) ;
當成Objective-C method 的傳入值的話都是要把型別寫在變數前面然後加上小括號,因些應該就要這樣寫
-(void) objcMethod:( int (^) (int) ) square; // square 變數的型別是 int (^) (int)
讀文至此是不是對Block有基本的認識? 接下來我們要談談Block相關的行為和特色
首先是來看一下在Block裡面存取外部變數的方法

存取變數
1. 可以讀取和Block pointer同一個scope的變數值:
{
int outA = 8;
int (^myPtr) (int) = ^(int a) {return outA+a;};
// block 裡面可以讀同一個scope的outA的值
int result = myPtr(3); // result is 11
}
我們再來看一個很有趣的例子

{
int outA = 8;
int (^myPtr) (int) = ^(int a) {return outA+a;};
// block 裡面可以讀同一個scope的outA的值
outA = 5; // 在呼叫myPtr之前改變outA的值
int result = myPtr(3); // result 的值還是 11並不是 8
}
 事實上呢,myPtr在其主體用到outA這個變數值的時候是做了一個copy的動作把outA的值copy下來。所以之後outA即使換了新的值對於myPtr裡copy的值是沒有影響到的。
要注意的是,這個指的值是變數的值,如果這個變數的值是一個記憶體的位置,換句話說,這個變數是個pointer的話,它指到的值是可以在block裡被改變的。
{
        NSMutableArray * mutableArray = [NSMutableArray arrayWithObjects:@"one",@"two",@"three",nil];
        int result = ^(int a) { [mutableArray removeLastObject];  return a*a;} (5);

        NSLog(@"test array %@", mutableArray);

}
原本mutableArray的值是{@"one",@"two",@"three"}在block裡被更改mutableArray所指向的物件後,mutableArray的值就會被成{@"one",@"two"}
2. 直接存取static 的變數
{
static int outA = 8;
int (^myPtr) (int) = ^(int a) {return outA+a;};
// block 裡面可以讀同一個scope的outA的值
outA = 5; // 在呼叫myPtr之前改變outA的值
int result = myPtr(3); // result 的值是 8,因為outA是個static 變數會直接反應其值
}
甚至可以在block裡面直接改變outA的值比如這樣寫
{
static int outA = 8;
int (^myPtr) (int) = ^(int a) { outA= 5; return outA+a;};
// block 裡面改變outA的值
int result = myPtr(3); // result 的值是 8,因為outA是個static 變數會直接反應其值

}
3. Block Variable
在某個變數前面如果加上修飾字__block 的話(注意block前有兩個下底線),這個變數又稱為block variable。那麼在block裡就可以任意修改此變數值,變數值的改變也可以知道。
{
    __block int num = 5;

    int (^myPtr) (int) = ^(int a) { return num++;};
    int (^myPtr2) (int) = ^(int a) { return num++;};
    int result = myPtr(0);
    result = myPtr2(0);
}
因為myPtr和myPtr2都有用到num這個block variable,最後result的值就會是7

生命周期和記憶體管理

因為block也是繼承自NSObject,所以其生命周期和記憶體的管理也就非常之重要。
block一開始都是被放到stack裡,換句話說其生命周期隨著method或function結束就會被回收,和一般變數的生命周期一樣。
關於記憶體的管理請遵循這幾個要點
1. block pointer的實體會在method或function結束後就會被清掉
2. 如果要保存block pointer的實體要用-copy指令,這樣block pointer就會被放到heap裡
    2.1 block 主體裡用到的block variable 也會被搬到heap 而有新的記憶體位置,且一並更新有用到這個block variable 的block都指到新的位置
    2.2 一般的variable值會被copy
    2.3 如果主體裡用到的variable是object的話,此object會被retain, block release時也會被release
    2.4 __block variable 裡用到的object是不會被retain的

首先來看一下這個例子

typedef int (^MyBlock)(int);

MyBlock genBlock();

int main(){
        MyBlock outBlock = genBlock();
        int result = outBlock(5);

        NSLog(@"result is %d",[outBlock retainCount] ); // segmentation fault
        NSLog(@"result is %d",result  );

        return 0 ;
}
MyBlock genBlock() {
        int a = 3;
        MyBlock inBlock = ^(int n) {
                return n*a;
        };
        return inBlock ;
}
此程式由genBlock裡產生的block再指定給main function的outBlock變數,執行這個程式會得到
Segmentation fault
(註:有時候把 genBlock裡的a 去掉就可以跑出結果的情形,這是系統cache住記憶體,並不是inBlock真得一直存在,久了還是會被回收,千萬不要以為是對的寫法)
表示我們用到了不該用的記憶體,在這個例子的情況下是在genBlock裡的inBlock變數在return的時候就被回收了,outBlock無法有一個合法的記憶體位置-retainCount就沒意義了。
如果這個時候需要保留inBlock的值就要用-copy指令,將genBlock改成
 MyBlock genBlock() {
        int a = 3;
        MyBlock inBlock = ^(int n) {
                return n*a;
        };
        return [inBlock copy]  ;
}
這樣[inBlock copy]的回傳值就會被放到heap,就可以一直使用(記得要release)
執行結果是
result is 1
result is 15

再次提醒要記得release outBlock。
如果一回傳[inBlock copy]的值就不再需要的時候可以這樣寫
 MyBlock genBlock() {
        int a = 3;
        MyBlock inBlock = ^(int n) {
                return n*a;
        };
        return [[inBlock copy] autorelease] ;
}
-copy指令是為了要把block 從stack搬到heap,autorelease是為了平衝retainCount加到autorelease oop ,回傳之後等到事件結束就清掉。

接下來是block存取到的local variable是個物件的型別,然後做copy 指令時
MyBlock genBlock() {
        int a = 3;
        NSMutableString * myString = [NSMutableString string];
        MyBlock inBlock = ^(int n) {
                NSLog(@"retain count of string %d",[myString retainCount]);
                return n*a;
        };
        return [inBlock copy] ;
}
結果會印出
retain count of string 2
這個結果和上面2.3提到的一樣,local variable被retain了
那再來試試2.4,在local variable前面加上__block
MyBlock genBlock() {
        int a = 3;
        __block NSMutableString * myString = [NSMutableString string];
        MyBlock inBlock = ^(int n) {
                NSLog(@"retain count of string %d",[myString retainCount]);
                return n*a;
        };
        return [inBlock copy] ;
}
執行的結果就是會
retain count of string 1

Block Copying注意事項
如果在Class method裡面做copying block動作的話
1. 在Block裡如果有直接存取到self,則self會被retain
2. 在Block裡如果取存到instance variable (無論直接或是從accessor),則self會被retain
3. 取存到local variable所擁有的object時,這個object會被retain

讓我們來看一個自訂的Class
@interface MyObject : NSObject {
        NSString * title;
        void (^myLog) (NSString * deco);
}

-(void) logName;
@end

@implementation MyObject
-(id) initWithTitle:(NSString * ) newTitle{
        if(self = [super init]){
                title = newTitle;
                myLog = [^(NSString * deco) { NSLog(@"%@%@%@",deco, title, deco );} copy];
        }
        return self;
}

-(void) logName{

 myLog(@"==");
}

-(void ) dealloc{

        [myLog release];
        [title release];
        [super dealloc];
}
@end
在main 裡使用如下

 MyObject * mObj = [[MyObject alloc] initWithTitle:@"Car"];
 NSLog(@"retainCount of MyObject is  %d",[mObj retainCount]  );
 [mObj logName];
其執行的結果為
retainCount of MyObject is  2
==Car==
因為在MyObject的建構子裡myLog這個block pointer用了title這個instance variable然後就會retain self也就是MyObject的物件。
盡量不要這樣寫,會造成retain cycle,改善的方法是把建構子改成這樣
-(id) initWithTitle:(NSString * ) newTitle{
        if(self = [super init]){
                title = newTitle;
                myLog = [^(NSString * deco) { NSLog(@"%@%@%@",deco, newTitle, deco );} copy];
        }
        return self;
}
在Block主體裡用newTitle這個變數而不是title。這樣self就不會被retain了。
最後談一個小陷井
void (^myLog) (void);
BOOL result ;
if(result)
    myLog = ^ {NSLog(@"YES");};

else
    myLog = ^ {NSLog(@"NO");};

myLog();

這樣很可能就會當掉了,因為myLog 實體在if 或是else結束後就被清掉了。要記得。
要用copy來解決這個問題,但要記得release。

2010年11月3日 星期三

Objecitive-C - Unit Test 設定

這篇文章主要是教導大家
怎麼在開發iOS 程的專案裡使用Unit Test。
主要的參考來源還是來自Apple的官方文件
 http://goo.gl/tDsLh
筆者自己實地演練一下來和大家分享一些心得
首先要和大家說Test有兩種
Logic Test
Application Test
這兩種都會和大家介紹
Logic Test主要就是在測試自己寫的Object有沒有logic上的問題在simulator上就可以測試
Application Test就是在測試整個iOS程式有沒有和我們想像的不一樣?文件上是寫要在Device上跑

Logic Test
首先我們來看看Logic Test的起手式也就是日文的手順
第一步就是打開我們的Project
如果沒有就新產生一個Project 叫NewApp好了 (本文是以iPhone SDK 4.1為測試環境)
 接下來要開啟一個新的Target叫LogicTests。從Target按下右鍵->Add...-> New Target
請選擇Unit Test Bundle 
接著命名為 NewLogicTests 
按下Finish之後呢會看到新增的Target
接下來我們要新增測試的Class,有個專名詞叫Test Case
首先在Groups & Files 先產生一個Group專門用來放測試用的Class,叫Tests
 接著在Tests裡新增一個Test Case叫NewLogicTests.m,先New File然後選iOS 裡的 Cocoa Touch Class , Objective-C test case class

記得要打勾.h也要產生,還有Target只能有NewLogicTests如圖
完成後可以在Tests這個Group看到NewLogicTests.h和NewLogicTest.m這兩個檔案
如果這個時候,我們選擇Target是NewLogicTests的時,就直接Build & Run
我們會看到3個error產生(如果是4.2就不會產生3個)

前兩個error是因為4.1版本的問題,需要採用 https://gist.github.com/586296 網友所提供的方法
就是把上面連結的檔案拉到Project裡就可以看到修正後的模樣(4.2無需做此動作)
 這個error要怎麼去掉呢?注意看一下NewLogicTests.h裡最上方有一行
#define USE_APPLICATION_UNIT_TEST 1
預設是做application test,但是我們要的是logic test,所以要改成
#define USE_APPLICATION_UNIT_TEST 0
我們可以在Build -> Build Result看到都是綠色的了,成功。

做測試呢第一件事就是產生error來看看是不是測試功能有沒有正常
於是我們在NewLogicTests.m檔裡加上
-(void) testFail{
    STFail(@"fail is not bad");
}
會.m長成這樣。
#import "NewLogicTests.h"

@implementation NewLogicTests

#if USE_APPLICATION_UNIT_TEST     // all code under test is in the iPhone Application

- (void) testAppDelegate {
   
    id yourApplicationDelegate = [[UIApplication sharedApplication] delegate];
    STAssertNotNil(yourApplicationDelegate, @"UIApplication failed to find the AppDelegate");
   
}

#else                           // all code under test must be linked into the Unit Test bundle

- (void) testMath {
       STAssertTrue((1+1)==2, @"Compiler isn't feeling well today :-(" );
}

-(void) testFail{
    STFail(@"fail is not bad");
}

#endif

@end
 Build Result 就又會看到錯誤了,不過這次是我們自己加的只是測試功能是不是正常。
 然後把 -(void) testFail{} 註解掉,就可以開始正常寫test case 了。

Application Test
接下來就是教大家設定Application Test
因為這個Test要用到UIApplication所以官方文件上是教大家在Device上面做測試
為了乾淨起見,再開另一個新的Project也叫NewApp但放在不同的資料夾
接著復製原有的Target NewApp只要在其上按右鍵 Duplicate

接著把新的Target命名為NewAppTesting
再新增一個Unit Test Bundle 的Target,在"Target"上按右鍵Add -> New Target
選擇Unit Test Bundle
取命為AppTests
之後會在Group & Files 看到新的Unit Test Bundle Target
然後我們新增Unit Test 的Test Case在Classes Group下Add -> New File 選Objective-C test case class 取名為AppTests把Target AppTests打勾
會看到.h, .m在Groups & Files


因為在用Application Test的時候需要有一個UIApplication在執行,所以我們要把NewAppTesting和AppTests這兩個Target關連起來,方法就是把AppTests拉到NewAppTesting底下
接下來把Products Group打開會看到一個叫AppTests.octest的紅紅的檔案
 接下來把這個檔案拉到剛剛的NewAppTesting這個Target 底下的Copy Bundle Resources
接下來就是在左上方把Target 選為NewAppTesting, 要用Device來跑
  
提醒大家一下,每個Target都有自己的plist哦,所以剛剛NewAppTesting的plist應該是在Resource下叫NewApp-Info copy.plist

在Console 會看到這樣的結果
列給大家看
Test Suite '/var/mobile/Applications/xxxxxxxxxxxxxxxxxxxxxxxx/NewApp.app/AppTests.octest(Tests)' started at 2010-11-04 03:23:23 GMT
Test Suite 'AppTests' started at 2010-11-04 03:23:23 GMT
Test Case '-[AppTests testAppDelegate]' started.
Test Case '-[AppTests testAppDelegate]' passed (0.000 seconds).
Test Suite 'AppTests' finished at 2010-11-04 03:23:23 GMT.
Executed 1 test, with 0 failures (0 unexpected) in 0.000 (0.004) seconds

Test Suite '/var/mobile/Applications/xxxxxxxxxxxxxxxxxx/NewApp.app/AppTests.octest(Tests)' finished at 2010-11-04 03:23:23 GMT.
Executed 1 test, with 0 failures (0 unexpected) in 0.000 (0.009) seconds

Test Suite 'All tests' finished at 2010-11-04 03:23:23 GMT.
Executed 1 test, with 0 failures (0 unexpected) in 0.000 (0.034) seconds
就是都通過測式了,接著就是要給一個自己的錯誤
在AppTest.m裡打上
-(void) testFail {
    STFail(@"Fault is not always bad.");
}
位置要放對
然後執行就會在Console看到
出現錯誤了,耶??
那接下來就可以開始測試,記得把-(void) testFail{}給註解掉