我是 Objective C 的新手,正在做一些对象练习。虽然像 Fraction* f = [[Fraction alloc] init ];
这样的东西有效,但每当我尝试做 Fraction c;
我得到 Interface type cannot be statically allocated
是否有在堆栈上分配对象的方法(就像在 C++ 中一样)?还是我做错了事?
最佳答案
从技术上讲,您可以(参见下面的代码),但您不应该这样做。此外,无论是在堆栈中还是在堆中,您只有一个指向对象的指针,而不是对象本身。也就是说,您应该编写 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;
}
}
alloca()
是非标准的、不安全的、不可移植的,并且容易出现堆栈溢出。
关于objective-c - Objective C 在栈上分配对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12423627/