Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C - Blocks and memory management?

__weak MyClass *selfReference = self;

dispatch_async(dispatch_get_main_queue(), ^{
        [selfReference performSomeAction];
    });
  • When do you need to pass a weak reference to a block?
  • Does this rule apply to dispatch_async as well as custom blocks?
  • Does a block copy the iVars used in it or does it retain them?
  • Who owns the variables initialized inside a block? Who should release them?
like image 924
aryaxt Avatar asked Aug 31 '12 15:08

aryaxt


People also ask

Does Objective-C have memory management?

Objective-C provides two methods of application memory management. In the method described in this guide, referred to as “manual retain-release” or MRR, you explicitly manage memory by keeping track of objects you own.

What is an Objective-C block?

An Objective-C class defines an object that combines data with related behavior. Sometimes, it makes sense just to represent a single task or unit of behavior, rather than a collection of methods.

What is automate memory management for Objective-C objects?

This is called Manual Retain Release (MRR). However, Xcode 4.2 introduced Automatic Reference Counting (ARC), which automatically inserts all of these method calls for you.

What are the two problems of memory management in iOS?

Memory Management Issues Freeing or overwriting data that is still in use. It causes memory corruption and typically results in your application crashing, or worse, corrupted user data. Not freeing data that is no longer in use causes memory leaks.


1 Answers

1, 2) Blocks retain the object-pointers in it (any blocks, dispatch_async blocks are nothing special). This usually isn't a problem, but can lead to retain-cycles, because the block can be associated with an owner object and that owner object (often self) might be retained by the block. In that case you should use a weak variable and then reassign it to a strong capture:

__weak MyClass *weakSelf = self;
self.block = ^{
    MyClass *strongSelf = weakSelf;
    ...
    [strongSelf ...];
    [strongSelf.property ...];
    [strongSelf->iVar ...];
 }

Note: If you access an iVar directly, the compiler will transform that into self->iVar and thus retains self!

3) Blocks only retain the pointers, they don't copy them.

4) Variables created inside a block belong to that block and will be released when that block goes out of scope.

like image 112
Fabian Kreiser Avatar answered Sep 21 '22 00:09

Fabian Kreiser