Last active
December 15, 2015 16:39
-
-
Save iamleeg/5290797 to your computer and use it in GitHub Desktop.
Creating objects on the stack in Objective-C
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 { | |
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]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(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 theNSObject
implementation of-dealloc
tries to release the memory).