天天看點

OC學習之道:關于Block的初級學習

轉自:http://blog.csdn.net/qq_31810357

<b></b>

"code" class="oc"&gt;  

//  

//  main.m  

//  copyright (c) 2015年 tongxing. all rights reserved.  

#import   

#import "student.h"  

typedef int(^blocktype)(int,int);  

int globalvariable = 200;  

int main(int argc, const charchar * argv[])  

{  

    @autoreleasepool {  

        //int (int a,int b)表示匿名函數的類型  

        //int (^ )(int a,int b)表示block的類型  

        //myblock實作的是匿名函數的實作體部分  

        int (^ myblock)(int a ,int b) =^int(int a ,int b){  

            return a+b;  

        };//這裡需要加分号,因為這整個部分相當于一個指派語句,大括号内容指派給塊變量myblock  

        //按照調用函數的方式調用塊對象  

        int value =   myblock(3,5);//通過myblock實作兩個整型數的求和,傳回值為int  

        nslog(@"%d",value);  

//寫⼀個 傳回值為整型 參數為nsstring(僅⼀一個參數)的block,實作将字元串轉換為整型的功能.  

        int (^strblock)(nsstring *str)=^int(nsstring *str){  

        int value =[str intvalue];  

        return value;  

            };  

        nsstring *str = @"123";  

        //使用block  

        nslog(@"%d",strblock(str));  

//練習,定義三個block求商/差/積  

        int (^cutblock)(int ,int )=^int(int a,int b){  

            return a-b;  

        };  

        int (^dealerblock)(int ,int)= ^(int a,int b){  

            return  a%b;  

        int (^rideblock)(int,int ) = ^(int a,int b){  

            return a*b;  

        nslog(@"%d",cutblock(3,5));  

        nslog(@"%d", dealerblock(3,5));  

        nslog(@"%d",rideblock(3,5));  

       //對于上面三個函數的類型都一樣,是以可以引入typedef來在#import下面進行重定義  

#pragma mark----給相同block類型進行重命名  

        blocktype myblock1 = ^int(int a,int b){//對于^後面的int可以省略,但是系統預設的是int型,是以如果是其他類型一定要寫上  

        nslog(@"%d",myblock1(4,5));  

        //.....  

#pragma mark----block與全局變量    

    //定義一個全局變量globalvariable  

        void (^block)(void) = ^(){//^(void)(),前面的傳回值類型void可以省略,但是後面的括号文法上定義是不可以省略(),但是經過測試沒有參數也可以省略  

            globalvariable++;//如果是全局變量可以直接被通路和修改  

            nslog(@"%d",globalvariable);  

        block();  

#pragma mark----block與局部變量  

       // int number =1;//局部變量需要加__block,否則會提示出錯  

      __block  int  number = 1;  

        void (^block1)(void) = ^(){  

            number++;//如果是局部變量不可以直接被通路和修改,必須在number前面加一個__block,這裡需要打兩個小_  

            nslog(@"%d",number);  

        block1();  

#pragma mark----block自動截取變量  

        int val = 10;  

        void (^blk)(void) = ^(){  

           // printf("val=%d\n",val);  

            nslog(@"%d",val);  

        val = 2;  

        blk();  

//上面這段代碼,輸出值是:val = 10.而不是2.block截獲自動變量的瞬時值。因為block儲存了自動變量的值,是以在執行block文法後,即使改寫block中使用的自動變量的值也不會影響block執行時自動變量的值。  

#pragma mark----block與數組排序  

        //關于數組的排序已經總結過,這裡做一個比較  

//使用系統自帶compare比較系統自帶對象  

        nsarray *strsarray =[nsarray arraywithobjects:@"abc",@"cdf",@"ade",@"feg", nil nil];  

        nsarray *newarray = [strsarray sortedarrayusingselector:@selector(compare:)];  

        nslog(@"%@",newarray);  

//使用block方式比較系統自帶對象  

        //該種方式是按block的文法按步驟來進行比較的,下面背注掉的是使用簡便的方式,兩者原理一樣  

        nscomparisonresult(^strblock1)(id obj1,id obj2)=^nscomparisonresult(id obj1,id obj2){  

            nsstring *result1 = (nsstring *)obj1;  

            nsstring *result2 = (nsstring *)obj2;  

            return [result1 compare:result2];  

        nsarray *resut3 = [strsarray sortedarrayusingcomparator:strblock1];//strblock1  

        nslog(@"%@--",resut3);  

//       nsarray *sortarray = [strsarray sortedarrayusingcomparator:^nscomparisonresult(id obj1, id obj2) {^nscomparisonresult(id obj1, id obj2)相當于上面的strblock1  

//           nsstring *result1 = (nsstring *)obj1;  

//           nsstring *result2 = (nsstring *)obj2;  

//           return [result1 compare:result2];  

//        }];  

//        nslog(@"%@",sortarray);  

        //對于系統自帶的對象和類都可以用compare方法,但是自定義的類需要自己重寫compare方法  

        //使用自定義compare方法對數組中得對象按照年齡進行排序,(數組中的對象為自定義類型的對象)  

        student *stu1 = [student studentwithname:@"劉亦菲" age:26 score:89.0];  

        student *stu2 = [student studentwithname:@"張飛" age:34 score:78.0];  

        student *stu3 = [student studentwithname:@"周冬雨" age:22 score:85.0];  

        nsmutablearray *stusarray = [nsmutablearray arraywithobjects:stu1,stu2,stu3 , nil nil];  

        [stusarray sortusingselector:@selector(studentcompare:)];  

        for (nsstring * str in stusarray) {  

            nslog(@"%@",str );  

        }  

//使用block方式對數組中得對象按照年齡進行排序,(數組中的對象為自定義類型的對象)  

        [stusarray sortusingcomparator:^nscomparisonresult(id obj1, id obj2) {  

            student *stu1 = (student *)obj1;//強制轉換成自定義類型  

            student *stu2 = (student *)obj2;  

            return  [stu1 studentcompare:stu2];  

        }];  

        for (nsstring *stri in stusarray) {  

            nslog(@"%@",stri);  

 //使用自定義的block實作對數組中的對象進行排序,基本處理方式與上述的處理系統對象相似,隻是如果不知道參數類型必須進行強制轉換  

       nscomparisonresult(^stublock)(id ob1,id ob2) =^ nscomparisonresult(id ob1,id ob2){  

        student *stud1 = (student *)ob1;//強制轉換  

        student *stud2 = (student *)ob2;  

           return [stud1 studentcompare:stud2];  

       };  

        [stusarray sortusingcomparator:stublock];//調用自定義塊  

    return 0;  

}  

自定義的student類的.h檔案和.m檔案如下:

.m檔案  

//  student.m  

//  lesson6  

//  created by lanou3g on 15-4-7.  

@implementation student  

//@synthesize _name ;  

//@synthesize _age;  

//@synthesize _score ;  

//自從xcode 4.4後,@property就獨攬了@property和@synthesize的功能。  

//-(void)setname:(nsstring *)name{  

//    _name = name;  

//}  

//-(void)setage:(int)age{  

//    _age = age;  

//-(nsstring *)name{  

//    return _name;  

//-(int)age{  

//   return  _age;  

//-(void)setscore:(float)score{  

//    _score = score;  

//-(float)score{  

//    return _score;  

-(id)initwithname:(nsstring *)name age:(int)age score:(float)score{  

    if (self = [super init]) {  

        _name = name;  

        _age = age;  

        _score = score;  

    }  

    return self;  

+(id)studentwithname:(nsstring *)name age:(int)age score:(float)score{  

    student *student = [[student alloc]initwithname:name age:age score:score];  

    return student;  

-(nscomparisonresult)studentcompare:(student *)student{  

    nscomparisonresult result1 = [[nsnumber numberwithint:self.age] compare:[nsnumber numberwithint:student.age]];  

    return result1;  

-(nsstring *)description{  

    return [nsstring stringwithformat:@"%@,%d",_name,_age];  

@end  

   歡迎分享本文,轉載請注明出處!