簡單說明 Category, Protocol, Property, Fast Enumation的功能
Category :
可用來在現有的類別(如果沒有程式碼)中新增method,但不能用來新增instance varible。
雖然也可用來覆載(override) method,但不建議這樣使用;如要改變己存在的method的動作,請用subclass的方式。
Sample:
PrettyPrintCategory.h
#import <Foundation/NSArray.h> // if Foundation not already imported
@interface NSArray (PrettyPrintElements) - (NSString *)prettyPrintDescription;
@end |
PrettyPrintCategory.m
#import "PrettyPrintCategory.h"
@implementation NSArray (PrettyPrintElements) - (NSString *)prettyPrintDescription {
// implementation code here...
}
@end |
使用時只要先import PrettyPrintCategory.h
之後建立NSArray物件後就可以使用prettyPrintDescription method.Protocol:
利用protocol可以在Objective-C中達成類似多重繼承的效果。
宣告時如有引用protocol,則一定要在implement時實作。
如要使用多個protocol,可使用<protocol1, protocol2>寫法。
在iphone開發中,protocol主要是用於delegate。
Protocol.h
@protocal nameOfProtocol // define protocol function here @end |
MyClass.h
@interface MyClass:NSObject<nameOfProtocol> @end |
MyClass.m
@implementation MyClass{ -(void)close{ } -(void)open{ } } @end |
Property:
是Objective-C 2.0中新增加的語法。利用這個語法,在precompiler時會幫我們產生getter及setter。 @property放在物件宣告的地方。基本語法如下:
@property(attributes, …) type propertyName;
Attributes間用”,”分開,可設定的屬性有:
1.getter,setter的名稱,如getter=getVaribleName
2.讀寫設定:
-
預設為readwrite,會產生getter與setter。
-
readonly表示沒有setter所以不能出現在等號的左邊。
3.setter設定
-
預設為assign,把等號右邊的數值與位址賦予等號左邊。
-
retain,只能用在objective-C的物件類型,在賦值的同時會呼叫retain,原本的值會被release釋放。
-
copy,用在Objective-C的物件類型,賦值時會自動呼叫copy,原本的值會被release釋放。此物件類型需實作NSCopying protocol。
4.getter設定
-
noatomic,預設是atomic(不寫就是用預設值,沒有atomic這個值),主要是用在多執行緒時,atomic保証可以取得正確的值,但效率較差。在手機上因效率考量,多用noatomic。
使用時在implementation中加入synthesize,語法如下
|
Sample:
|
Fast Enumeration
:
是Objective-C 2.0的新功能。用來快速存取一個collection中的物件。
此機制可以防止在列舉過程中被修改,以確保列舉的安全性。
FastEnumeration的語法如下:
|
expression需遵從NSFastEnumeration協定,如Foundation中的NSArray, NSDictionary, NSSet等
參考資料:
http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-SW31