1

我在初始化 NSArray 并向其添加整数时遇到问题。这是我的代码,我在我想要完成的事情中发表了评论。添加对象时,我的应用程序崩溃,但我不知道我是否也正确清除了数组。

//CREATE AND INITIALIZE AN ARRAY
NSArray *ticket;                                                        
ticket = [[NSArray alloc] init];

//slotA,slotB,slotC are of type NSInteger that I am trying to add
//to the array (THIS CRASHES)

[ticket addObject:[NSNumber numberWithInt:slotA]];
[ticket addObject:[NSNumber numberWithInt:slotB]];
[ticket addObject:[NSNumber numberWithInt:slotC]];

//I never got to this line of code but I think it has to be wrong
//because this would throw the whole //array away. I dont want it
//to be thrown away I just wanna clear it out but keep it instanciated.

[ticket release];

我试过这个,但它说我“错过了一个前哨函数调用”

NSArray *ticket;
NSString *sltA=[NSString stringWithFormat:@"%d", slotA];
NSString *sltB=[NSString stringWithFormat:@"%d", slotB];
NSString *sltC=[NSString stringWithFormat:@"%d", slotC];
ticket = [[NSArray alloc] initWithObjects:sltA,sltB,sltC];

另外,我是否必须将整数更改为字符串才能将它们放入数组中?

4

2 回答 2

4

将 NSArray 更改为 NSMutableArray。这将允许您添加和删除对象。

NSArray 是一个在创建后不会更改的数组。

NSMutableArray 只是 NSArray 的一个子类,它有许多函数可以帮助你在数组中的任何位置添加和删除对象。

于 2010-07-06T02:17:25.107 回答
-1

代码看起来是正确的(从技术上讲,您应该使用+numberWithInteger:而不是+numberWithInt:,但它肯定不会导致崩溃。)您看到的崩溃是什么?您可以发布 GDB/Xcode 的输出吗?

于 2010-07-06T02:15:16.667 回答