Skip to content

Instantly share code, notes, and snippets.

@janodev
Forked from iamleeg/gist:5290797
Last active December 15, 2015 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janodev/5292003 to your computer and use it in GitHub Desktop.
Save janodev/5292003 to your computer and use it in GitHub Desktop.
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