Weak/weak/weak

The weak keyword is used in the following scenarios:

  1. Weak is broken in ARC to avoid circular references, such as the weak modifier for the delegate property.

  2. The XIB IBOutlet control property is weak by default, but it can also be strong. Why not use strong? Because:

Because if there’s an outer chain then the view must exist in the XIB or in the storyboard, the view already has a strong reference to it. In addition to use storyboard xib (no) created by vc, there will be a private array called _topLevelObjectsToKeepAliveFromStoryboard strong reference all the top level object, So it doesn’t matter if your outlet is declared weak.

Should IBOutlets be strong or weak under ARC?

  1. The __weak usage scenarios are:

Now look at some code:

@interface TestViewController ()
@property(nonatomic, copy) void (^block)(void);
@end
@implementation TestViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.block = ^{
        [self funtionA];
    };
    self.block();
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:YES];
}

- (void)funtionA {
    NSLog(@"FNNTION -- funtionA");
}

- (void)dealloc {
    NSLog(@"FUNTION -- dealloc");
}
Copy the code

There’s a code that says, when we pop our controller, dealloc doesn’t get called, because there’s a circular reference, self and block are strongly holding each other, self is strongly referencing the block, Block in turn forces a reference to self inside the block (because the block makes a copy of the object inside the block onto the heap).

What can you do to break this circular reference? __weak is used.

Modify the code to:

__weak typeof(self) weakSelf = self; //typeof(instance): identifies the variable type based on the arguments in parentheses and returns the type. self.block = ^{ [weakSelf funtionA]; }; self.block();Copy the code

This breaks the loop reference strong hold, the controller is released normally, and the delloc executes normally.

2. Use of assign

Assign is often used to modify data of primitive data types, as well as objects.

3. Weak and assign are different

The weak keyword acts as a weak reference. The counter of the referenced object is not incresed by 1 and is automatically set to nil when the referenced object is released, so weak does not cause wild Pointers.

Assign will cause wild pointer problems if you modify the object. It is safe to modify primitive data types. If you assign an object, the pointer will not be set to nil when the object is released, and sending messages to the object will crash.

Delegate is assigned or weak?

A. weak B. weak C. weak D. weak

Assign does not automatically set the Delegate to nil when the delegate object is released, produces wild Pointers, and crashes if a message is sent to the delegate object.

The weak modifier avoids this problem.