-1

有没有办法重新分配变量以在 for 循环中为其提供不同的内存地址

我正在使用 ARC

代码的主要部分在这里;

- (void) deal:(BOOL)isDefault
{
    player = [[Player alloc] init];
    appDel = [[BlackjackAppDelegate alloc] init];
    appDel.playersArray = [[NSMutableArray alloc] init];
    appDel.discardPile = [[NSMutableArray alloc] init];

    // Initial Deal

    int i; // Current Card for player
    int j; // Current Player

    if (isDefault)
    {
        startingCardCount = 7;
        numberOfPlayers = 4;
    }

    for (int temp = 0; temp < numberOfPlayers; temp++)
    {
        [self addPlayersWithNumber:temp];
    }

    // Loops through number of cards supposed to be in hand (if default settings: use 7 cards)
    for (i = 0; i < startingCardCount; i++)
    {
        // Loop through number of players (if default settings: use 4 players)
        for (j = 0; j < numberOfPlayers; j++)
        {
            //Player *tempPlayer = [appDel.playersArray objectAtIndex:j];
            Card *card = [Card generateCardWithAppDel:appDel];
            Player *tempPlayer = [appDel.playersArray objectAtIndex:j];

            [tempPlayer.hand addObject:card];
            [self refreshPlayerIndex:j withPlayer:tempPlayer];
        }
    }
}
- (void) addPlayersWithNumber:(NSInteger)playerNumber
{
    // THIS VARIABLE I WANT TO "REALLOCATE" EACH TIME THIS METHOD IS CALLED
    Player *tempPlayer = [[Player alloc] init];
    tempPlayer.number = playerNumber;

    [appDel.playersArray addObject:player];
}

感谢您能给我的任何帮助,我真的需要解决这个问题,因为我正在添加到一个数组并在交易方法的不同部分进行操作(如图所示)

编辑:

播放器.h:

//
//  Player.h
//  Blackjack
//
//  Created by Zach Ross-Clyne on 02/03/2013.
//  Copyright (c) 2013 Avicode. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "BlackjackAppDelegate.h"

@interface Player : NSObject
{
    NSInteger type;
    NSInteger number;
    NSMutableArray *hand;
}

@property (nonatomic, strong) NSMutableArray *hand;
@property (nonatomic) NSInteger type;
@property (nonatomic) NSInteger number;

@end

播放器.m

//
//  Player.m
//  Blackjack
//
//  Created by Zach Ross-Clyne on 02/03/2013.
//  Copyright (c) 2013 Avicode. All rights reserved.
//

#import "Player.h"

@implementation Player

@synthesize number, hand, type;

- (id) init
{
    hand = [[NSMutableArray alloc] init];
    return self;
}

@end
4

2 回答 2

4

我认为你误解了一个错误。请看以下内容:

Player *tempPlayer = [[Player alloc] init];
tempPlayer.number = playerNumber;

[appDel.playersArray addObject:player];

你在那里做的是:

  1. 创建一个播放器,tempPlayer
  2. 将实例变量添加player到您的playersArray

因此tempPlayer,您创建的每一个都是独一无二的,并且没有一个被放入您的数组中。

于 2013-05-03T19:48:17.027 回答
1
tempPlayer.number = playerNumber;
[appDel.playersArray addObject:player];

应该:

tempPlayer.number = playerNumber;
[appDel.playersArray addObject:tempPlayer];
于 2013-05-03T19:49:36.710 回答