显示标签为“Block”的博文。显示所有博文
显示标签为“Block”的博文。显示所有博文

2013年7月1日星期一

Block Guide





Introduction

Block objects are a C-level syntactic and runtime feature. They are similar to standard C functions, but in addition to executable code they may also contain variable bindings to automatic (stack) or managed (heap) memory. A block can therefore maintain a set of state (data) that it can use to impact behavior when executed.

You can use blocks to compose function expressions that can be passed to API, optionally stored, and used by multiple threads. Blocks are particularly useful as a callback because the block carries both the code to be executed on callback and the data needed during that execution.

Declaring and Using a Block

You use the ^ operator to declare a block variable and to indicate the beginning of a block literal. The body of the block itself is contained within {}, as shown in this example (as usual with C, ; indicates the end of the statement):
int multiplier = 7;
int (^myBlock)(int) = ^(int num) {
    return num * multiplier;
};
The example is explained in the following illustration:
image: ../Art/blocks.jpg
Notice that the block is able to make use of variables from the same scope in which it was defined.
If you declare a block as a variable, you can then use it just as you would a function:
int multiplier = 7;
int (^myBlock)(int) = ^(int num) {
    return num * multiplier;
};
 
printf("%d", myBlock(3));
// prints "21"

Conceptual Overview

Block objects provide a way for you to create an ad hoc function body as an expression in C, and C-derived languages such as Objective-C and C++. In other languages and environments, a block object is sometimes also called a “closure”. Here, they are typically referred to colloquially as “blocks”, unless there is scope for confusion with the standard C term for a block of code.

Usage

Blocks represent typically small, self-contained pieces of code. As such, they’re particularly useful as a means of encapsulating units of work that may be executed concurrently, or over items in a collection, or as a callback when another operation has finished.
Blocks are a useful alternative to traditional callback functions for two main reasons:
  1. They allow you to write code at the point of invocation that is executed later in the context of the method implementation.
    Blocks are thus often parameters of framework methods.
  2. They allow access to local variables.
    Rather than using callbacks requiring a data structure that embodies all the contextual information you need to perform an operation, you simply access local variables directly.

Declaring a Block Reference

Block variables hold references to blocks. You declare them using syntax similar to that you use to declare a pointer to a function, except that you use ^instead of *. The block type fully interoperates with the rest of the C type system. The following are all valid block variable declarations:
void (^blockReturningVoidWithVoidArgument)(void);
int (^blockReturningIntWithIntAndCharArguments)(int, char);
void (^arrayOfTenBlocksReturningVoidWithIntArgument[10])(int);
Blocks also support variadic (...) arguments. A block that takes no arguments must specify void in the argument list.
Blocks are designed to be fully type safe by giving the compiler a full set of metadata to use to validate use of blocks, parameters passed to blocks, and assignment of the return value. You can cast a block reference to a pointer of arbitrary type and vice versa. You cannot, however, dereference a block reference via the pointer dereference operator (*)—thus a block's size cannot be computed at compile time.
You can also create types for blocks—doing so is generally considered to be best practice when you use a block with a given signature in multiple places:
typedef float (^MyBlockType)(float, float);
 
MyBlockType myFirstBlock = // ... ;
MyBlockType mySecondBlock = // ... ;

2013年3月16日星期六

Blocks and Variables

对于 Block 的用法,一定要注意下面的红字。

如果使用的是自定义的 Block,并且这个 Block 在某个对象的生命周期内会一直存在,一定要注意红字,遵循规则。
否则,则很容易出现 retain cycle。
所以,现在官方的 Api 提供的 block 使用,也是类似动画这种 block,它只在某个对象的生命周期内出现瞬间,然后销毁,这样就不会有 retain cycle。


Objective-C Objects

  1. In a manually reference-counted environment, local variables used within the block are retained when the block is copied. Use of instance variables within the block will cause the object itself to be retained. If you wish to override this behavior for a particular object variable, you can mark it with the __block storage type modifier.
  2. If you are using ARC, object variables are retained and released automatically as the block is copied and later released.

Note In a garbage-collected environment, if you apply both __weak and __block modifiers to a variable, then the block will not ensure that it is kept alive.


  1. If you use a block within the implementation of a method, the rules for memory management of object instance variables are more subtle:
  2. If you access an instance variable by reference, self is retained;
  3. If you access an instance variable by value, the variable is retained.

The following examples illustrate the two different situations:

dispatch_async(queue, ^{
      // instanceVariable is used by reference, self is retained
      doSomethingWithObject(instanceVariable);
  });
  id localVariable = instanceVariable;
  dispatch_async(queue, ^{
      // localVariable is used by value, localVariable is retained (not self)
      doSomethingWithObject(localVariable);
  });


C++ Objects
In general you can use C++ objects within a block. Within a member function, references to member variables and functions are via an implicitly imported this pointer and thus appear mutable. There are two considerations that apply if a block is copied: 

2013年3月15日星期五

BlocksKit


BlocksKit Reference

http://zwaldowski.github.com/BlocksKit/Documentation/


老的 BlocksKit 到 1.5.2



新的 BlocksKit 迁移到了



  1. BlocksKit 是 ARC 的。
  2. BlocksKit 使用了libffi,使用源码的时候,不能添加 libffi 里面的 dlmalloc.c 的文件,不然在 free() 的时候报错,虽然编译通过,但无法运行。
  3. 也不能完全删除 dlmalloc.c 文件,只是不添加 xcode 工程里面,如果完全删除,则 closures.c 就会 找不到这个文件。
  4. a question