Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Creating objects on the stack in Objective-C
#import <Foundation/Foundation.h>
#include <stdlib.h>
#include <objc/runtime.h>
@interface A : NSObject
@property (assign) int meaning;
@end
@implementation A
- (id)init {
self = [super init];
if (self) _meaning = 42;
return self;
}
@end
#define Using(obj,cls) id obj = nil;\
{ size_t size = class_getInstanceSize([cls class]);\
obj = alloca(size);\
memset(obj, 0, size); }\
object_setClass(obj, [cls class]);
int main(int argc, char *argv[]) {
@autoreleasepool {
Using(a, A);
[a init];
NSLog(@"meaning: %d", [a meaning]);
}
}
@al45tair
Copy link

al45tair commented May 9, 2013

(c.f. https://gist.github.com/iamleeg/5540103)

Unlike its C++ cousin, this doesn't cause superclass fragility, and can't suffer from the C++ member variable issue.

It is still vulnerable to the problem of floating references (since ObjC objects are expected to be reference counted, something could call -retain and then expect the object to be available later), and as with the C++ version, -dealloc won't be called (this is both a good and a bad thing, because it means some objects won't get to clean up, but it may well prevent a crash when the NSObject implementation of -dealloc tries to release the memory).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment