Objective-C基本功 -Category, Protocol, Property, Fast Enumation

簡單說明 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

协议,就是使用了这个协议后就要按照这个协议来办事,协议要求实现的方法就一定要实现。

委托,顾名思义就是委托别人办事,就是当一件事情发生后,自己不处理,让别人来处理。
当一个Aview 里面包含了Bview
bview需要修改aview界面,那么这个时候就需要用到委托了。
需要几个步骤
1。首先定一个协议
2。aview实现协议中的方法
3。bview设置一个委托变量
4。把bview的委托变量设置成aview,意思就是 ,bview委托aview办事情。
5。事件发生后,用委托变量调用aview中的协议方法

 


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,語法如下
@synthesize propertyName [, propertyName2...];
 

Sample:
// Myclass.h

@interface MyClass:NSObject{

NSString * MyString;

NSString *MyString2;

}

@property (copy, noatomic, getter=getMyString1)  NSString * MyString;

@property (copy, noatomic)  NSString * MyString2;

@end;

//MyClass.m

@implementation MyClass

    @synthesize MyString;

    @synthesize MyString2;

@end
 


Fast Enumeration:
是Objective-C 2.0的新功能。用來快速存取一個collection中的物件。
此機制可以防止在列舉過程中被修改,以確保列舉的安全性。
FastEnumeration的語法如下:

for ( type newVariable in expression ) { statements } 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

 

本文来自CSDN博客,转载请标明出处:

http://blog.csdn.net/husoso/archive/2010/05/24/5620553.aspx

posted @ 2011-09-06 22:01  痴人指路  阅读(358)  评论(0编辑  收藏  举报