gpt4 book ai didi

objective-c - NSNumber numberWithInt 在数字 >= 13 时崩溃

转载 作者:搜寻专家 更新时间:2023-10-30 20:03:55 27 4
gpt4 key购买 nike

我是 Objective-C 的新手。我已经通读了 a similar question但我不知道如何用这些信息解决我的问题。

基本上,我是这样做的:

NSMutableArray* array1 = [[NSMutableArray alloc] initWithCapacity: 1];
NSNumber *n1 = [NSNumber numberWithInt: 12];
[array1 addObject: n1];
NSMutableArray* array2 = [[NSMutableArray alloc] initWithCapacity: 1];
NSNumber *n2 = [NSNumber numberWithInt: 13];
[array2 addObject: n2];

将 NSNumber 12 添加到数组中工作得很好,但添加 13(或任何更高的值)却不行;程序在运行时崩溃(没有错误消息,生成的堆栈转储文件完全空白)。如果重要的话,我正在 Cygwin 中使用 gcc 进行编译。我知道这可能与我上面提到的问题中的保留计数有关,但我不知道如何解决。即使我注释掉最后一行,它也会崩溃……所以它会在 numberWithInt 调用时崩溃,这意味着如果我为 n2 添加一个保留语句,它无论如何都没有机会被调用。

编辑:因为我被要求提供更多代码,这里是我为测试这个问题而制作的文件:

#import <stdio.h>
#import <Foundation/NSArray.h>
#import <Foundation/NSValue.h>

int main( int argc, const char *argv[] )
{
printf("1.\n");
NSMutableArray* array1 = [[NSMutableArray alloc] initWithCapacity: 1];
NSNumber *n1 = [NSNumber numberWithInt: 12];
[array1 addObject: n1];
NSMutableArray* array2 = [[NSMutableArray alloc] initWithCapacity: 1];
NSNumber *n2 = [NSNumber numberWithInt: 13];
[array2 addObject: n2];
printf("2.\n");

return 0;
}

这会打印“1”。然后崩溃,如上所述。这是我的生成文件:

CYGWIN_GNUSTEP_PATH=/cygdrive/c/GNUstep
CXX = gcc
MAIN = DummyGame
SOURCES = DummyGame.m
OBJECTS = $(SOURCES:%.m=%.o)
COMP_FLAGS = -std=c99 -I $(CYGWIN_GNUSTEP_PATH)/GNUstep/System/Library/Headers -L $(CYGWIN_GNUSTEP_PATH)/GNUstep/System/Library/Libraries -fconstant-string-class=NSConstantString
LINK_FLAGS = $(COMP_FLAGS) -lobjc -lgnustep-base

all: $(MAIN)

$(MAIN): $(OBJECTS)
$(CXX) -o $@ $^ $(LINK_FLAGS)

%.o: %.m $(HEADERS)
$(CXX) -c $< $(COMP_FLAGS)

clean:
$(RM) $(MAIN) $(OBJECTS)

最佳答案

尝试用一行围绕您的代码(您已放置在 main 中)以创建然后耗尽自动释放池:

NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init];
NSMutableArray* array1 = [[NSMutableArray alloc] initWithCapacity: 1];
NSNumber *n1 = [NSNumber numberWithInt: 12];
[array1 addObject: n1];
NSMutableArray* array2 = [[NSMutableArray alloc] initWithCapacity: 1];
NSNumber *n2 = [NSNumber numberWithInt: 13];
[array2 addObject: n2];
[pool drain];

关于objective-c - NSNumber numberWithInt 在数字 >= 13 时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7165735/

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