I'd like to recursively call a block from within itself. In an obj-c object, we get to use "self", is there something like this to refer to a block instance from inside itself?
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- back button text does not change
- iOS (objective-c) compression_decode_buffer() retu
- how to find the index position of the ARRAY Where
相关文章
- 现在使用swift开发ios应用好还是swift?
- TCC __TCCAccessRequest_block_invoke
- xcode 4 garbage collection removed?
- Unable to process app at this time due to a genera
- How can I add media attachments to my push notific
- didBeginContact:(SKPhysicsContact *)contact not in
- Custom Marker performance iOS, crash with result “
- Converting (u)int64_t to NSNumbers
There is no
self
for blocks (yet). You can build one like this (assuming ARC):The
__block
is needed so we can setblockSelf
to the block after creating the block. The__weak
is needed because otherwise the block would hold a strong reference to itself, which would cause a strong reference cycle and therefore a memory leak. Thecopy
is needed to make sure that the block is copied to the heap. That may be unnecessary with newer compiler versions, but it won't do any harm.The following recursive block code will compile and run using ARC, GC, or manual memory management, without crashing, leaking, or issuing warnings (analyzer or regular):
Important considerations:
You have to declare the block variable as
__block
:Fun story! Blocks actually are Objective-C objects. That said, there is no exposed API to get the
self
pointer of blocks.However, if you declare blocks before using them, you can use them recursively. In a non-garbage-collected environment, you would do something like this:
It is necessary to apply the
__block
modifier toblock_self
, because otherwise, theblock_self
reference insidefibonacci
would refer to it before it is assigned (crashing your program on the first recursive call). The__weak
is to ensure that the block doesn't capture a strong reference to itself, which would cause a memory leak.