block

This is a block

^{
    NSLog(@"This is from a block");
}

a block with arguments

^(double dividend, double divisor){
    double quotient = dividend/divisor;
    return quotient;
}

although blocks look like functions, they can be stored in variables. Like other variables, block variables are declared and then assigned values.

//declare the block variable
void (^devowelizer) (id, NSUInteger, BOOL *);

void : return type of block

^    : indication that this is a block

devowelizer: name of block variable

comma-delimited arguments

//assign a block to the variable

devowelizer =  ^(id string, NSUInteger i, BOOL *stop){

    NSMutableString *newString=[NSMutableString stringWithString:string];
    for (NSString *s in vowels){
        NSRange fullRange = NSMakeRange(0,[newString length]);
        [newString replaceOccurrencesOfString:s
                                   withString:@""
                                      options:NSCaseInsensitiveSearch
                                        range:fullRange];
    }

    [newStrings addObject:newString];

};//end of block assignment

Passing in a block

Because devowelizer is a variable, you can pass it as an argument. NSArray has a method called enumerateObjectsUsingBlock: This method expects a block as its sole argument, it will execute that block once for each object in the array.

[oldStrings enumerateObjectsUsingBlock:devowelizer];

 

Add a check at the beginning of the block

devowelizer = ^(id string, NSUInteger i, BOOL *stop){
    NSRange yRange = [string rangeOfString:@"y"
                                       options:NSCaseInsensitiveSearch];

    //did i find a y?
    if(yRange.location != NSNotFound){
         *stop = YES;
         return;
    }

    ...
};

typedef

Block syntax can be confusing, but you can make it friendlier using the typedef keyword.

Remember that tyepdef belongs at the top of the file or in a header, outside of any method implementations.

#import <Foundation/Foundation.h>

typedef void (^ArrayEnumerateBlock)(id,NSUInteger,BOOL *);
...

ArrayEnumerateBlock devowelizer;

 

 

 

 

posted on 2012-06-12 10:53  grep  阅读(334)  评论(0编辑  收藏  举报