NSNumber numberWithInt crashing on numbers >= 13
I'm pretty new to Objective-C. I've read through a similar question but I can't figure out how to solve my problem with that information.
B开发者_运维知识库asically, I'm doing this:
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];
Adding the NSNumber 12 to the array works perfectly fine, but adding 13 (or anything higher) does not; the program crashes at runtime (no error messages, and the stackdump file produced is completely blank). I'm compiling with gcc in Cygwin, if that matters. I understand that this is probably related to retain counts, as in the question I mentioned above, but I don't know how to fix it. Even if I comment out the last line, it crashes... so it's crashing right at the numberWithInt call, meaning that if I add a retain statement for n2, it won't have a chance to get called anyway.
edit: Since I was asked for more code, here's the file I made in order to test this problem:
#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;
}
This prints "1." and then crashes, as above. Here is my 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)
Try surrounding your code (which you've placed in main) with a line to create and then drain an auto release pool:
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];
Try the following:
Release
array1
andarray2
as youalloc
ed these:[array1 release]; [array2 release];
Create and release an autoreleasepool:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
...
[pool release];
精彩评论