2013-08-24 70 views
3

你好我正在一个项目上工作,我试图添加一个NSUInteger到一个NSMutableArray。一般来说,我是Objective-C和C的新手。当我运行应用程序NSLog显示为空。添加NSUInteger到NSMutableArray

我很感激任何人都可以提供的帮助。

这里是我的代码

-(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; 
} 
+0

NSUInteger是“标”,而不是一个“对象”。您只能将“对象”添加到NSArray。但是,您可以将NSNumber添加到NSArray,而NSNumber是数字类型的通用“包装器”类。请参阅NSNumber的规格。 –

回答

10

NSArray(连同其子类NSMutableArray一起)只支持对象,你不能原生值,将其添加。

退房的-addObject:

- (void)addObject:(id)anObject 

签名正如你可以看到它预计id作为参数,这大致意味着任何对象

所以你必须包装在NSNumber比如你的整数如下

[self.flipCardIndexes addObject:@(index)]; 

其中@(index)syntactic sugar[NSNumber numberWithInt:index]

然后,为了从阵列提取时,将其转换回NSUInteger,你要“解包”,它如下

NSUInteger index = [self.flipCardIndexes[0] integerValue]; // 0 as example 
+0

考虑到用户的经验,它也可能有助于解释如何从阵列中取回'NSUInteger'。 – rmaddy

+0

@rmaddy你是对的,补充说。谢谢 –

2

只能添加对象NSMutableArrays。 addObject接受id类型的对象,这意味着它将接受一个对象。

但是,NSIntegers和NSUIntegers不是对象。它们只是被定义为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宏定义为整数和长整数。

要将此添加到您的数组中,您需要先将其转换为对象。 NSNumber是Objective C类,允许您存储任意类型的数字。为了生成NSNumber,你需要你的numberWithInt方法,将你的变量作为参数传递。

NSNumber *number = [NSNumber numberWithInt:card]; 

既然你的变量被包装在一个对象中,你可以将它添加到数组中。

[self.flipCardIndexes addObject:number]; 

最后,如果你想在未来的时间来检索元素,你必须删除的对象,然后将其转换回你可以使用一个int值。致电

NSNumber *number = [self.flipCardIndexes objectAtIndex:index]; 

其中,索引是您试图检索的卡的索引。接下来,您必须通过调用integerValue将此值转换为整数。

NSUInteger *value = [number integerValue];