2013-03-06 2 views
0

Я использую версию Xcode 4.6. В приложении для iPhone и iPad, которое я делаю, я сделал функцию под названием dealCard. Вот оно:Почему мои функции не меняют значения моих внешних переменных?

- (void)dealCard : (UIImageView *)cardImage : (int)card : (int)suit : (BOOL)aceBool : (int) cardValue : (int)total 
{ 
suit = arc4random() % 4; 
card = arc4random() % 13; 
if (suit == 0) 
{ 
    //set images 

if (suit == 1) 
{ 
    //set images 
} 

if (suit == 2) 
{ 
    //set images 
} 

if (suit == 3) 
{ 
    //set images 
} 
if (card < 10 && card != 0) 
{ 
    NSLog(@"Setting cardValue"); 
    cardValue = card+1; 
} 
else if (card != 0) 
{ 
    NSLog(@"Setting cardValue"); 
    cardValue = 10; 
} 
else 
{ 
    NSLog(@"Setting cardValue"); 
    aceBool = YES; 
    if (total + 11 <= 21) 
    { 
     cardValue = 11; 
    } 
    else 
    { 
     cardValue = 1; 
    } 

} 
total = total + cardValue; 
NSLog(@"Total = %d cardValue = %d",total,cardValue); 
NSLog(@"playerTotal = %d playerCard3Value = %d",playerTotal,playerCard3Value); 
} 

Далее вниз страницы, которую я поставил:

[self dealCard: playerCard3Image : playerCard3 : playerSuit3 : playerCard3ace : playerCard3Value : playerTotal]; 

Моя проблема заключается в cardValue. На выходе написано «Setting cardValue», а затем номера переменных экземпляра правы, но два других неверны. ИгрокTotal считывает все, что было до того, как была получена эта карта, и playerCard3Value читает 0. Чтобы дать вам некоторый контекст, эта функция вызывается не тогда, когда первая или вторая карта обрабатывается, а когда третья и так далее. Первые две функции не обрабатываются. Кто-нибудь знает, почему это происходит?

+0

ли это быть из-за рамки переменных? – PsyKzz

+0

@Matt PsyK - Как я могу сделать их глобальными? Я просто объявляю их в файле .h как: 'int playerCard3Value;' –

+0

К сожалению, я не знаю obj-c или xcode, чтобы комментировать. – PsyKzz

ответ

1

Объектно-ориентированное программирование - это прекрасная вещь. Кодовый это очень быстро, чтобы показать вам, как это работает ...

// 
// PlayingCard.h 
// 

#import <Foundation/Foundation.h> 

@interface PlayingCard : NSObject 

- (id)initWithSuit:(NSInteger)suit value:(NSInteger)value; 
- (BOOL)isAce; 
- (BOOL)isFace; 

@end 


// 
// PlayingCard.m 
// 

#import "PlayingCard.h" 

@interface PlayingCard() 
@property(nonatomic, assign) NSInteger suit; 
@property(nonatomic, assign) NSInteger value; 

@end 

@implementation PlayingCard 

- (id)initWithSuit:(NSInteger)suit value:(NSInteger)value { 
    self = [self init]; 
    if (self) { 
     _suit = suit; 
     _value = value; 
    } 
    return self; 
} 

- (BOOL)isAce { 
    return self.value == 0; 
} 

- (BOOL)isFace { 
    return self.value > 10; 
} 

- (NSString *)suitName { 
    switch (self.suit) { 
     case 0: 
      return @"spades"; 
      break; 
     case 1: 
      return @"diamonds"; 
      break; 
     case 2: 
      return @"clubs"; 
      break; 
     case 3: 
      return @"hearts"; 
      break; 

     default: 
      return @""; 
      break; 
    } 
} 

// so it prints nicely. you should consider making the suits enums 
- (NSString *)description { 
    return [NSString stringWithFormat:@"%@: suit:%@, value:%d", [super description], [self suitName], self.value]; 
} 

@end 


// 
// CardDeck.h 
// 

#import <Foundation/Foundation.h> 

@class PlayingCard; 

@interface CardDeck : NSObject 

+ (id)cardDeck; 
- (void)shuffle; 
- (NSUInteger)count; 
- (PlayingCard *)dealOne; 

@end 

// 
// CardDeck.m 
// 

#import "CardDeck.h" 
#import "PlayingCard.h" 

@interface CardDeck() 
@property(nonatomic,strong) NSMutableArray *cards; 
@end 

@implementation CardDeck 

+ (id)cardDeck { 

    CardDeck *deck = [[self alloc] init]; 
    for (NSInteger suit = 0; suit < 4; suit++) { 
     for (NSInteger value = 0; value < 13; value++) { 
      PlayingCard *card = [[PlayingCard alloc] initWithSuit:suit value:value]; 
      [deck.cards addObject:card]; 
     } 
    } 
    return deck; 
} 

- (id)init { 
    self = [super init]; 
    if (self) { 
     _cards = [NSMutableArray array]; 
    } 
    return self; 
} 


- (void)shuffle { 
    NSMutableArray *shuffledCards = [NSMutableArray array]; 
    for (int i=0; i<52; i++) { 
     int randomIndex = arc4random_uniform(52-i); 
     [shuffledCards addObject:[self.cards objectAtIndex:randomIndex]]; 
     [self.cards removeObjectAtIndex:randomIndex]; 
    } 
    self.cards = shuffledCards; 
} 

- (NSUInteger)count { 
    return self.cards.count; 
} 


- (PlayingCard *)dealOne { 

    PlayingCard *card = [self.cards lastObject]; 
    [self.cards removeLastObject]; 
    return card; 
} 

@end 

Называйте это, как это ...

CardDeck *deck = [CardDeck cardDeck]; 
// try it with and without shuffle 
[deck shuffle]; 
while (deck.count) { 
    PlayingCard *card = [deck dealOne]; 
    NSLog(@"%@", card); 
} 
Смежные вопросы