是否有办法重新分配变量以在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];
}
感谢你能给我的任何帮助,我真的需要修复它,我正在添加一个数组并在交易方法的不同部分进行操作(如图所示)
编辑:
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
Player.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
答案 0 :(得分:4)
我认为你误解了一个错误。请看以下内容:
Player *tempPlayer = [[Player alloc] init];
tempPlayer.number = playerNumber;
[appDel.playersArray addObject:player];
你在做什么:
tempPlayer
; player
添加到playersArray
因此,您创建的每个tempPlayer
都是唯一的,并且它们都不会被放入您的数组中。
答案 1 :(得分:1)
tempPlayer.number = playerNumber;
[appDel.playersArray addObject:player];
应该是:
tempPlayer.number = playerNumber;
[appDel.playersArray addObject:tempPlayer];