gpt4 book ai didi

Objective-C:如何在 GNUStep 中启用 ARC?

转载 作者:太空狗 更新时间:2023-10-30 03:29:16 25 4
gpt4 key购买 nike

Objective-C/ARC/内存管理问题已经在 SO 上被解决了,但这一个似乎与现有的略有不同。

我一直在尝试将 Objective-C 与 GNUStep 和 Clang 结合使用。我已经下载了库显然是 ARC 等现代 Objective-C 功能所必需的; block 工作并且 @autoreleasepool 连同相关的编译器标志被编译器接受。 AppKit GUI 工具包可以工作,队列调度程序也可以。

我的理解(如果正确的话)是 alloced 对象会自动设置为在“父”堆栈框架的 @autoreleasepool 退出时释放,并且释放会减少引用计数。然而,编译器并不哀叹手动 [super dealloc] 并容忍手动 autoreleasesreleases,这意味着 ARC 甚至没有切换上。

有人可能会想象谷歌搜索 GNUStep ARC ~enable 会产生一些我遗漏的编译器标志,但事实并非如此。

这是一些示例代码。它是一个围绕 C99 bool 多维数组的对象包装器,它在 initfree 中被 malloc 编辑d 在 dealloc 中,我收集到的是 ARC 代码中 dealloc 的少数合法用途之一。请注意,在@autoreleasepool 完成后,deallocputs 不会被调用,尽管其中只创建了一个引用。但是,手动releaseautorelease 效果很好。

#import <stdbool.h>
#import <stdio.h>
#import <stdlib.h>

#import <Foundation/Foundation.h>

@interface Area : NSObject {
bool *area;
size_t width, height;
}

- (id) initWithWidth:(size_t)aWidth height:(size_t)aHeight;
- (void) dealloc;
- (void) display;
@end

@implementation Area

- (id) initWithWidth:(size_t)aWidth height:(size_t)aHeight {
self = [super init];
width = aWidth;
height = aHeight;
area = malloc((sizeof *area) * aWidth * aHeight);

for (size_t y = 0; y < aHeight; ++y) {
for (size_t x = 0; x < aWidth; ++x) {
area[(aHeight * y) + (aWidth * x)] = true;
}
}

return self;
}

- (void) dealloc {
free(area);
puts("DEALLOCATED");
}

- (void) display {
for (size_t y = 0; y < height; ++y) {
putchar('|');
for (size_t x = 0; x < width; ++x) {
putchar(area[(height * y) + (width * x)]
? '#'
: ' ');
}
puts("|");
}
}

@end

int main(void)
{
@autoreleasepool {
id area = [[Area alloc] initWithWidth:10 height:10];
[area display];
}
return EXIT_SUCCESS;
}

我的编译脚本(一旦我开始工作,我将使用合适的 makefile):-

#!/bin/sh

INC_FLAG=`gnustep-config --variable=GNUSTEP_SYSTEM_HEADERS`
LIB_FLAG=`gnustep-config --variable=GNUSTEP_SYSTEM_LIBRARIES`

clang -o main main.m \
-I $INC_FLAG \
-L $LIB_FLAG \
\
-fblocks \
-fobj-arc \
-fconstant-string-class=NSConstantString \
-D_NATIVE_OBJC_EXCEPTIONS \
\
-pthread \
-lgnustep-base \
-ldispatch \
-lgnustep-gui \
-lobjc

我一直假设 autorelease 应该被推断为在 @autoreleasepool 中创建的对象。

提前致谢!

最佳答案

解决方案:Josh Caswell 指出我的编译器标志fobj-arc 应该是fobjc-arc。鉴于 Clang 没有给出此标志无效的指示,我将把这个答案留给其他人。

关于Objective-C:如何在 GNUStep 中启用 ARC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19895777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com