Add support for @defer Objective-C compiler directive

Originator:nobrien
Number:rdar://21684961 Date Originated:06-Jul-2015 09:44 AM
Status:Open Resolved:
Product:Developer Tools Product Version:Xcode-beta (7A121l)
Classification:Feature (New) Reproducible:Not Applicable
 
With the excellent addition of “defer” to Swift, this seems like the perfect opportunity to also offer an @defer directive in Objective-C.  This is actually simple enough to express currently as a macro in Objective-C, but built in compiler support would provide the powerful construct as a built in feature of the language just like Swift has.  Below I’ve outlined how one must go about doing a defer today in Objective-C (which requires a header include/import) and how making @defer a directive would be a very natural addition to the language.


// some helper declarations

#define _custom_macro_concat(a, b) a##b
#define custom_macro_concat(a, b) _custom_macro_concat(a, b)
typedef void(^custom_defer_block_t)();
NS_INLINE void custom_deferFunc(__strong custom_defer_block_t *blockRef)
{
    custom_defer_block_t actualBlock = *blockRef;
    actualBlock();
}


// the core macro

#define custom_defer(deferBlock) \
__strong custom_defer_block_t custom_macro_concat(__custom_stack_defer_block_, __LINE__) __attribute__((cleanup(custom_deferFunc), unused)) = deferBlock

// use via macro in code

#include <custom_defer.h>

- (void)foo
{
    FILE *file = fopen(…);
    custom_defer(^{
        if (file) {
            fclose(file);
        }
    });

    // continue code where any stack exit will lead to the defer being executed
}

// if we had an @defer directive instead

- (void)foo
{
    FILE *file = fopen(…);
    @defer(^{
        if (file) {
            fclose(file);
        }
    });

    // continue code where any stack exit will lead to the defer being executed
}

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!