Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 5: Blocks Implementation > Capturing Objects

Capturing Objects

We saw examples using integer variables. Next, let’s see what will happen when an object is used from a Block. In the next source code, an object of the NSMutableArray class is created and the assigned variable has ownership of it. Because the scope of the variable, which qualified with __strong, is left immediately, the object is released and discarded.

{
    id array = [[NSMutableArray alloc] init];
}

Listing 5–7 uses the variable “array” in a Block literal.

Listing 5–7. Capturing an object

blk_t blk;
{
    id array = [[NSMutableArray alloc] init];
    blk = [^(id obj) {
        [array addObject:obj];
        NSLog(@"array count = %ld", [array count]);
    } copy];
}
blk([[NSObject alloc] init]);
blk([[NSObject alloc] init]);

blk([[NSObject alloc] init]);

  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial