简体   繁体   中英

Keeping a strong pointer to a local object

I encountered this thing in a book which I am reading and it got me thinking:

"When you allocate a block, it is created on the stack. This means that, even if you were to keep a strong reference to it, calling it later would result in a crash because the memory would be destroyed as soon as you leave the method in which it was defined."

I thought if I have a strong pointer to something, it is kept alive ? Does this mean this does not apply for objects allocated on the stack?

I am trying to think of an example without using blocks...(eg, of pointer - maybe an ivar- pointing to a stack allocated object which gets destroyed even though the pointer is alive)

Objects are never allocated on the stack in Objective-C. Blocks are special however, since they are stack allocated. So if you want to retain a pointer to a block, you must first copy it by using Block_copy and use the copy, then release it with Block_release . This must be done if the block is to be used after the scope it was declared in is destroyed. More on the matter here: https://developer.apple.com/library/mac/documentation/cocoa/Conceptual/Blocks/Articles/bxUsing.html (under "Copying Blocks"). Yet again though, this does not apply to regular objects.

Blocks can be messaged like objects. To move them from the stack to the heap, just "copy" them.

void (^stackBlock)() = [^(){
    NSLog(@"Hello world");
} copy];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM