在Index处将对象添加到Objective C数组

Bry*_*yan 1 iphone cocoa-touch insert objective-c nsmutablearray

我有一个合成的NSMutableArray - theResultArray.我想在特定索引(0-49)处插入NSNumber或NSInteger对象.出于某种原因,我永远无法在我的数组中获得任何值.每个索引返回nil或0.

    NSInteger timeNum = time;
    [theResultArray insertObject:[NSNumber numberWithInt:timeNum] atIndex:rightIndex];
    NSLog(@"The right index is :%i", rightIndex);
    NSLog(@"The attempted insert time :%i", time);
    NSNumber *testNum = [theResultArray objectAtIndex:rightIndex];
    NSLog(@"The result of time insert is:%i", [testNum intValue]);
Run Code Online (Sandbox Code Playgroud)

我在viewDidLoad中alloc-init theResultsArray.时间是整数.我一直在尝试上面代码的不同组合无济于事.

控制台输出:

StateOutlineFlashCards[20389:20b] The right index is :20
StateOutlineFlashCards[20389:20b] The attempted insert time :8
StateOutlineFlashCards[20389:20b] The result of time insert is:0
Run Code Online (Sandbox Code Playgroud)

pet*_*erb 5

除非我误读,你不是在插入一个NSInteger,而是试图取出一个NSNumber吗?这是两种完全不同的数据类型.你得到奇怪的结果并不让我感到惊讶.

此外,NSInteger不是一个对象,因此您不能将其粘贴到数组中.您可能希望分配一个带有该整数的NSNumber并将其放入.

尝试类似的东西: [theResultArray addObject:[NSNumber numberWithInteger:timeNum] atIndex:rightIndex];

同样,当您检索该值时,您需要将其取消包装:

NSLog(@"The result of time insert is:%i", [testNum integerValue])`;
Run Code Online (Sandbox Code Playgroud)

同样,当您检索该值时,您需要将其取消包装:

坦率地说,我甚至有点惊讶,甚至编译.