很長時間都是在學習各位大神的力作,並汲取了不少養料,在此一並謝過各位大神了。
當然了,好東西是要跟大家一起分享的,最近發現了幾個非常不錯的個人站點,都是介紹IOS開發的,其中有唐巧、破船之長、池建強、王維等各位,其中不乏供職於騰訊和阿裡這樣的IT巨頭,希望大家也能從他們的博客中學習到一些技術之外的東西。就不再啰嗦啦,附上地址:http://www.ityran.com/archives/4647
這幾天在學習IOS7 CookBook,因為沒有找到中文版,就硬著頭皮啃原著吧,還真學到了不少東西,很值得跟大家分享,今天先把block裡邊關於變量引用的部分寫一下吧,都是自己的讀書感悟,如有錯誤,懇請各位高人指教。
首先,block在我們平時編程過程中,使用的不多。起碼我基本不用的\(^o^)/~
但在GCD多線程裡,基本全是block的身影,所以多了解一下,在處理IOS7的多任務時,還是蠻有好處的。
1.聲明方法
block的聲明方法:返回值類型(^方法名)(變量類型,變量類型)(參數)
例如://返回值為字符串類型,帶有一個整形變量的名稱為intToString的blcok
NSString *(^intToString)(NSUInteger)=^(NSUInteger parma)
{
NSString *result=[NSString stringWithFormat:@"%lu",(unsigned long) parma];
return result;
};使用過程中,這樣調用就可以了:
NSString *result=intToString(10000);
NSLog(@"result:%@",result);2.關於變量的調用
在IOS程序中,大致有三種變量,全局變量、block之外的局部變量和block內聲明的局部變量。
block對在block內生命的變量是有絕對的read write權限的,但是對於全局變量和在block之外的局部變量就沒有那麼大的權限了。
對於全局變量而言,若要進行讀寫,只有調用get set方法了
對於在block外部聲明的局部變量,block是有讀權限的,若要增加write權限,需要在變量前添加__block前綴。
代碼的力量總是無窮無盡的,下面就來看一下具體是怎麼實現的吧
- (void)simpleMethod
{
//若要在block內對外部聲明的變量進行write操作,要加上__block前綴
//否則只有read權限
__block NSUInteger outsideVariable=10;
NSMutableArray *array=[[NSMutableArray alloc]initWithObjects:@"obj1",@"obj2", nil];
[array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
//對於block內聲明的變量而已,具有read write權限
NSUInteger insideVarible=20;
outsideVariable=50;
NSLog(@"outSide variable=%lu",(unsigned long)outsideVariable);
NSLog(@"inside variable=%lu",(unsigned long)insideVarible);
//調用self
NSLog(@"self:%@",self);
//使用.屬性 需使用set get方法
self.stringParoperty=@"helloWorld";
NSLog(@"self.stringProperty:%@",self.stringParoperty);
return NSOrderedSame;
}];
}在獨立的block函數內,是不能直接調用self的,只有通過參數傳遞的方式才能對self進行訪問
//不能在獨立的block內使用self,必須以參數形式傳遞
//使用.屬性時,需要set get方法進行讀寫設置
void (^incorrectBlockObject)(id)=^(id selfParam)
{
NSLog(@"self:%@",selfParam);
[selfParam setStringParoperty:@"Block Object"];
NSLog(@"self.stringProperty:%@",[selfParam stringParoperty]);
};- (void)scopeTest
{
NSUInteger integerValue=10;
BlockWithNoparam myBlock=^{
NSLog(@"Integer value inside the block:%lu",(unsigned long)integerValue);
};
integerValue=20;
myBlock();
NSLog(@"Integer value inside the block:%lu",(unsigned long)integerValue);
}在控制台,你會發現,輸出的值是10和20 ,卻不是改變變量後的20 和20.
要改變這一現象,跟前面提到過的一樣,只要在integerValue前添加__block 前綴即可,剛興趣的朋友可以試一下哦\(^o^)/~
關於這一部分的測試代碼,我會放在下載頻道,有需要的同學,可以直接下載。
http://download.csdn.net/detail/jidiao/7283035