IOS efficient development of two --ARC with block thing

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Block is a particular piece of code can capture the context.

Block can access the variables defined in the block, when used in a block, to create a copy of it will be in the scope of each scalar variable.

If the self has a block, then the change in the block instance variables, you will make mistakes.

For example:

1 self.block = ^(NSString *aString)
2 {
3     self.aLabel.text = aString;
4 });

This code, self retains the block, and the block retains the self, will lead to circular retention. Very dangerous.

If you do not use ARC, you can use __block and __unsafe_unretained to copy a copy of the reference is not preserved.

 1 //For example: (without ARC)
 2 __block id safeSelf = self;
 3 self.block = ^(NSString *aString)
 4 {
 5     safeSelf.aLabel.text = aString;
 6 });
 7  
 8 //(ARC)
 9 __weak id safeSelf = self;        //ios 5
10 // __unsafe_unretained id safeSelf = self; //ios 4
11 self.block = ^(NSString *aString)
12 {
13     safeSelf.aLabel.text = aString;
14 });

Before arc, we can free the CF* object into a NS* object, this is called his bridge. After using arc, we need to specify a transfer of ownership.

At present there are provided in the arc modifier:

1.__bridge

2.__bridge_retained

3.__bridge_transfer


The first modifier __bridge is a common conversion, says it does not need to increase the reference count, no change of ownership.

The second is in the C pointer types, increase the reference count.

The third is the Core Foundation pointer type into a obj-c pointer variable, the reference count of +1. If an object is created using the Core Foundation method, and use arc to manage the object's memory, you can use this.


Common mistakes in arc transplantation

1 cast obj-c pointer C pointer (or vice versa)

2 in the arc in the void* pointer forced into ID type (or conversely turn), if you want to change, we must use modifiers

For example: id selfPointer = (__bridge void *)self;

3 in the structure or (Union) in the aggregation is used by the obj-c object

4 using NSAutoreleasePool


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Truman at November 24, 2013 - 10:15 PM