Objective-C Cheat Sheet and Quick Reference
URL : http://www.raywenderlich.com/4872/objective-c-cheat-sheet-and-quick-reference
Objective-C Cheat Sheet and Quick Reference
URL : http://www.raywenderlich.com/4872/objective-c-cheat-sheet-and-quick-reference
在新的iOS API中block被大量用來取代傳統的delegate和callback,而新的API會大量使用block主要是基於以下兩個原因:
可以直接在程式碼中撰寫等會要接著執行的程式,直接將程式碼變成函數的參數傳入函數中,這是新API最常使用block的地方。 可以存取區域變數,在傳統的callback實作時,若想要存取區域變數得將變數封裝成結構才能使用,而block則是可以很方便地直接存取區域變數。
—
Objective C Blocks: Summary, Syntax & Best Practices
http://amattn.com/p/objective_c_blocks_summary_syntax_best_practices.html
定義
- (void) sayHello: (NSString*) name;
implementation :
- (void) sayHello: (NSString*) name { NSMutableString *message = [[NSMutableString alloc] initWithString:@"Hello there "]; [message appendString:name]; NSLog(message); [message release]; } //
simple.m 宣告 sayHello method:
#import "Simple.h" @implementation Simple - (void) sayHello: (NSString *) name { NSMutableString *message = [[NSMutableString alloc] initWithString:@"Hello there "]; [message appendString:name]; NSLog(message); [message release]; } @end //
simple.h
#import @interface Simple : NSObject { } -(void) sayHello: (NSString *) name; @end //
main 呼叫 sayHello method:
#import #import "Simple.h" int main(int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Simple * mySimple = [[Simple alloc] init]; [mySimple sayHello:@"James"]; [mySimple release]; int retVal = UIApplicationMain(argc, argv, nil, nil); [pool release]; return retVal; } //