NSNumber numberWithInt在数字> = 13时崩溃

时间:2011-08-23 18:22:59

标签: objective-c debugging nsnumber

我对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(或更高的值)则不然;程序在运行时崩溃(没有错误消息,并且生成的stackdump文件完全空白)。如果重要的话,我正在Cygwin中使用gcc进行编译。 我知道这可能与保留计数有关,就像我上面提到的问题一样,但我不知道如何修复它。即使我注释掉最后一行,它也会崩溃......所以它会在numberWithInt调用时崩溃,这意味着如果我为n2添加一个retain语句,它就没有机会被调用。

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

#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”然后崩溃,如上所述。这是我的makefile:

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)

2 个答案:

答案 0 :(得分:5)

尝试围绕您的代码(已放置在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];

答案 1 :(得分:0)

尝试以下方法:

  1. 发布array1array2 alloc这些:

    [array1 release]; [array2 release];

  2. 创建并发布autoreleasepool:

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    ...

    [pool release];