13.07.2015 Views

Beginning Objective-C pdf - EBook Free Download

Beginning Objective-C pdf - EBook Free Download

Beginning Objective-C pdf - EBook Free Download

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 4: <strong>Objective</strong>-C Language Features 95Listing 4-25. Blocks as Return Values-(dispatch_block_t)methodWithExplictReturnValue{return ^{ NSLog(@"I am in a block"); };}-(id)methodWithIdReturnValue{return [^{ NSLog(@"I am in a block"); } copy];}You can use blocks as parameters, too. The code in Listing 4-26 demonstrates how blocks canbe used to enumerate over the contents of an array without using a for loop.Listing 4-26. Array Enumeration Using BlocksNSArray *array = ...; //some array[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {NSLog(@"Array index %d is %@", idx, obj);}];If you take a look in NSArray.h, you can find the declaration for this method. Listing 4-27includes a naïve implementation of how this method might work.Listing 4-27. Block Declaration, Assignment, and Invocation- (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block{for (NSInteger i = 0; i < self.count; i++){__block BOOL stop;block([self objectAtIndex:i], i, &stop);if (stop)return;}}This brings us to another important feature of blocks: lexical closures.Lexical ClosuresBlock objects can use variables that are in lexical scope when they are declared. The variablesare captured by the block and can be accessed from within the block code, as shown inListing 4-28.Listing 4-28. Blocks as Lexical Closuresvoid (^exampleBlock)(void);if (YES) //just to create a new lexical closurewww.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!