Skip to content

Instantly share code, notes, and snippets.

@janodev
Forked from iamleeg/gist:5290797
Last active Dec 15, 2015
Embed
What would you like to do?
This creates an Objective-C object in the stack. ARC code.
#import <Foundation/Foundation.h>
#include <stdlib.h>
#include <objc/runtime.h>
@interface A : NSObject
@property (assign) int meaning;
@end
@implementation A
- (id)init {
if ([super init]) {
_meaning = 42;
}
return self;
}
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
// allocate and zero stack memory
size_t size = class_getInstanceSize([A class]);
id obj = (__bridge_transfer id) alloca(size);
memset((__bridge void*)obj, 0, size);
// set class and initialize the object
object_setClass(obj, [A class]);
obj = [obj init];
NSLog(@"meaning: %d", [obj meaning]);
// transfer ownership from ARC to CF so ARC doesn't
// try to improperly free the stack allocated memory
CFTypeRef ref = (__bridge_retained CFTypeRef) obj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment