2013-08-24 72 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];