Note that there are some explanatory texts on larger screens.

plurals
  1. POCompactly disable arc-retain-cycles warning for self-referencing blocks
    text
    copied!<p>I'm writing an API that involves event handling, and I'd like to be able to use blocks for the handlers. The callbacks will often want to access or modify self. In ARC mode, Clang warns that blocks referencing self are likely to create a retain cycle, which seems like a helpful warning that I want to keep on in general.</p> <p>However, for this portion of my API, the lifecycle of the callback and the containing object are maintained externally. I know I can break the cycle when the object should be deallocated. </p> <p>I can turn off the retain cycle warning on a per file basis with <code>#pragma clang diagnostic ignored "-Warc-retain-cycles"</code>, but that disables the warning for the entire file. I can surround the blocks with a <code>#pragma clang diagnostic push</code> and <code>pop</code> around that warning, but that makes the blocks ugly.</p> <p>I can also get the warning to go away by referencing a __weak variable pointing to self instead of referencing self directly, but that makes the blocks far less pleasant to use.</p> <p>The best solution I've come up with is this macro that does the diagnostic disabling around the block:</p> <pre><code>#define OBSERVE(OBJ, OBSERVEE, PATH, CODE) \ [(OBJ) observeObject:(OBSERVEE) forKeyPath:(PATH) withBlock:^(id obj, NSDictionary *change) { \ _Pragma("clang diagnostic push") \ _Pragma("clang diagnostic ignored \"-Warc-retain-cycles\"") \ do { CODE; } while(0); \ _Pragma("clang diagnostic pop") \ }]; </code></pre> <p>That works, but it's not very discoverable for API users, it doesn't allow nested observers, and it interacts poorly with XCode's editor. Is there a better way to disable or avoid the warning?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload