Ios 将NSUMutableArray添加到NSIMutableArray
您好,我正在处理一个项目,我正在尝试向NSMutableArray添加一个整数。我不熟悉Objective-C和C。当我运行应用程序时,NSLog显示null 我非常感谢任何人能提供的帮助 这是我的密码Ios 将NSUMutableArray添加到NSIMutableArray,ios,objective-c,nsmutablearray,nsuinteger,Ios,Objective C,Nsmutablearray,Nsuinteger,您好,我正在处理一个项目,我正在尝试向NSMutableArray添加一个整数。我不熟悉Objective-C和C。当我运行应用程序时,NSLog显示null 我非常感谢任何人能提供的帮助 这是我的密码 -(NSMutableArray *)flipCardAtIndex:(NSUInteger)index { Card *card = [self cardAtIndex:index]; [self.flipCardIndexes addObject:index]; i
-(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;
}
只能将对象添加到NSMutableArray。addObject接受id类型的对象,这意味着它将接受一个对象 但是,nsInteger和nsInteger不是对象。它们只是被定义为C风格的变量
#if __LP64__ || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif
如您所见,它们只是基于typedef宏定义为int和long
要将其添加到数组中,首先需要将其转换为对象。NSNumber是Objective C类,允许您存储任何类型的数字。要生成NSNumber,需要使用numberWithInt方法,将变量作为参数传递
NSNumber *number = [NSNumber numberWithInt:card];
既然变量已包装在对象中,就可以将其添加到数组中
[self.flipCardIndexes addObject:number];
最后,如果希望在将来检索元素,则必须删除该对象,然后将其转换回可以使用的int值。召唤
NSNumber *number = [self.flipCardIndexes objectAtIndex:index];
其中index是您尝试检索的卡的索引。接下来,必须通过调用integerValue将该值转换为整数
NSUInteger *value = [number integerValue];
NSArray
(及其子类NSMutableArray
)仅支持对象,不能向其添加本机值
请查看您的签名
正如您所看到的,它期望id
作为参数,这大致意味着任何对象
因此,您必须将整数包装在NSNumber
实例中,如下所示
[self.flipCardIndexes addObject:@(index)];
NSUInteger index = [self.flipCardIndexes[0] integerValue]; // 0 as example
其中@(索引)
表示[NSNumber numberWithInt:index]
然后,为了在从数组中提取时将其转换回NSUInteger
,您必须按如下方式“展开”
[self.flipCardIndexes addObject:@(index)];
NSUInteger index = [self.flipCardIndexes[0] integerValue]; // 0 as example
根据用户的经验,还可以解释如何从数组中获取
NSUInteger
。NSUInteger是一个“标量”,而不是一个“对象”。只能将“对象”添加到NSArray。但是,您可以将NSNumber添加到NSArray,NSNumber是数字类型的通用“包装器”类。请参阅规范中的NSN编号。