Objective C 在堆栈上分配对象

Cem*_*mre 4 stack object objective-c

我是 Objective C 的新手,正在对对象进行一些练习。虽然类似的东西Fraction* f = [[Fraction alloc] init ];有效,但每当我尝试这样做时,Fraction c;我都会得到Interface type cannot be statically allocatedIs There Anyway to allocate object on the stack (like in c++) ? 或者我正在尝试错误的事情?

Jan*_*ano 5

从技术上讲,您可以(请参阅下面的代码),但您不应该这样做。而且,无论是在栈还是堆中,你只有一个指向对象的指针,而不是对象本身。也就是说,你应该写Fraction *c,而不是Fraction c

// Allocate an Objective-C object on the stack.
// Original code By Graham Lee: 
// https://gist.github.com/iamleeg/5290797     

#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;
    }
}
Run Code Online (Sandbox Code Playgroud)

alloca()是非标准的、不安全的、不可移植的、并且容易出现堆栈溢出。