我正在尝试掌握 Objective C 和 Cocoa,所以我可能在这里使用了错误的术语。
我已经为我的主 AppDelegate.h 和 AppDelegate.m 读取的一副纸牌制作了一个 Objective C 类,它有两个方法,deckOfCards 和 pickACard。deckOfCards 只是一个 NSMutableArray,每种卡片类型都以字符串形式写出,然后在 pickACard 中创建一个新数组,如下所示:
-(void)pickACard
{
DeckOfCards *newDeck = [[DeckOfCards alloc] init];
int r = arc4random() % 52;
NSLog (@"The card you picked is: %@, and there are %i cards left", [newDeck objectAtIndex:r], [newDeck count]);
[newDeck removeObjectAtIndex:r];
}
但是 XCode 说我不能在这个新数组上使用 objectAtIndex 和 removeObjectAtIndex,所以我不能随机选择一张卡片,然后通过删除数组的那部分来“从包中删除它”。
这在deckOfCards 中确实有效,但是当它被AppDelegate.m 调用时,它会创建一个新数组,所以我会得到不同的卡片,但永远不会从包中删除超过一张。
我猜我没有正确创建这个新数组。
为了更清楚起见,DeckOfCards.h 是这样的:
#import <Foundation/Foundation.h>
@interface DeckOfCards : NSObject
{
@private
}
-(void) deckOfCards;
-(void) pickACard;
@end
DeckOfCards.m 是这样的:
@implementation DeckOfCards
-(void)deckOfCards
{
NSMutableArray *deckOfCards = [NSMutableArray arrayWithObjects:
@"One of Hearts", @"Two of Hearts"..., nil];
}
-(void)pickACard
{
DeckOfCards *newDeck = [[DeckOfCards alloc] init];
int r = arc4random() % 52;
NSLog (@"The card you picked is: %@, and there are %i cards left",[newDeck objectAtIndex:r], [newDeck count]);
[newDeck removeObjectAtIndex:r];
}
@end