-
-
Save janodev/5292003 to your computer and use it in GitHub Desktop.
This creates an Objective-C object in the stack. ARC code.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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