将NSUInteger添加到NSMutableArray
你好我正在一个项目上工作,我想添加一个NSUInteger到一个NSMutableArray。 一般来说,我是Objective-C和C的新手。 当我运行的应用程序NSLog显示空。
我会很感激任何人都可以提供帮助。
这是我的代码
-(NSMutableArray *)flipCardAtIndex:(NSUInteger)index { Card *card = [self cardAtIndex:index]; [self.flipCardIndexes addObject:index]; if(!card.isUnplayable) { if(!card.isFaceUp) { for(Card *otherCard in self.cards) { if(otherCard.isFaceUp && !otherCard.isUnplayable) { int matchScore = [card match:@[otherCard]]; if(matchScore) { otherCard.unplayable = YES; card.unplayable = YES; self.score += matchScore * MATCH_BONUS; } else { otherCard.faceUp = NO; self.score -=MISMATCH_PENALTY; } break; } } self.score -=FLIP_COST; } card.faceUp = !card.isFaceUp; } NSLog(@"%@",self.flipCardIndexes[self.flipCardIndexes.count-1]); return self.flipCardIndexes; }
NSArray
(及其子类NSMutableArray
)只支持对象,不能为其添加本地值。
查看-addObject:
的签名-addObject:
- (void)addObject:(id)anObject
正如你所看到的,它期望id
作为参数,这大致意味着任何对象 。
所以你必须把你的整数包装在一个NSNumber
实例中,如下所示
[self.flipCardIndexes addObject:@(index)];
其中@(index)
是[NSNumber numberWithInt:index]
语法糖 。
然后,为了将它从数组中提取时转换回NSUInteger
,你必须“解开”它如下
NSUInteger index = [self.flipCardIndexes[0] integerValue]; // 0 as example
您只能将对象添加到NSMutableArrays。 addObject接受idtypes的对象,这意味着它将接受一个对象。
然而,NSInteger和NSUIntegers不是对象。 它们只是被定义为C风格的variables。
#if __LP64__ || NS_BUILD_32_LIKE_64 typedef long NSInteger; typedef unsigned long NSUInteger; #else typedef int NSInteger; typedef unsigned int NSUInteger; #endif
正如你所看到的,它们被定义为基于typedefmacros的整数和长整数。
要将其添加到您的数组中,您需要先将其转换为一个对象。 NSNumber是Objective C类,允许您存储任意types的数字。 为了使NSNumber,你会想你numberWithInt方法,传递你的variables作为参数。
NSNumber *number = [NSNumber numberWithInt:card];
现在你的variables被包装在一个对象中,你可以将它添加到数组中。
[self.flipCardIndexes addObject:number];
最后,如果要在将来检索元素,则必须删除该对象,然后将其转换回可以使用的int值。 呼叫
NSNumber *number = [self.flipCardIndexes objectAtIndex:index];
其中index是您试图检索的卡的索引。 接下来,您必须通过调用integerValue将此值转换为整数。
NSUInteger *value = [number integerValue];