Цель -C: Создание NSMutableDictionary или NSMutableArray - PullRequest
0 голосов
/ 02 апреля 2012

Для моего приложения для iPhone я хочу управлять значениями в NSMutableDictionary или NSMutableAarray.

Я хочу сохранить рейтинг в этом формате

round   player1  player2
  1        6        8
  2        7        9
--        --        --

здесь, в моем случае, число раундов будет фиксированным значением, предположим, что 10, и общее число игроков будет равно 2, что также является фиксированным.

но пользователь может отправлять свои оценки в произвольном порядке, но одним нажатием кнопки. Значения

 score for round  "10" for both the player   enter
 score for round  "2"  for both the player   enter

так, как управлять словарем или массивом, который мог бы помочь мне в их извлечении снова легко?

Пожалуйста, помогите и предложите.

Спасибо

Ответы [ 4 ]

4 голосов
/ 02 апреля 2012

Почему только массивы или словари на объектно-ориентированном языке?

@interface RoundResults : NSObject

@property (nonatomic, assign) NSInteger playerOneScore;
@property (nonatomic, assign) NSInteger playerTwoScore;

@end

@interface GameTotal : NSObject

- (void)setResults: (RoundResults *)results forRound: (NSInteger)round;
- (RoundResults *)resultsForRound: (NSInteger)round;
- (NSUInteger)countOfResults;

@end
3 голосов
/ 02 апреля 2012
//You can use combination of mutable array and dictionary to handle each round and player score

NSMutableArray *mutArrayRound=[[NSMutableArray alloc] initWithCapacity:10];


//--EDIT-------------------------------------------------------------------

//You need to do it somewhere so that it'll not give error for [mutArrayRound insertObject: atIndex:]

mutDic=[[NSMutableDictionary alloc] init];

for(int i=0;i<10;i++)
{
    [mutArrayRound addObject:mutDic];
}

[mutDic release];

//-------------------------------------------------------------------------

NSMutableDictionary *mutDic=[[NSMutableDictionary alloc] initWithCapacity:2];
[mutDic setValue:@"Score_Valaue" forKey:@"player1-Score"];
[mutDic setValue:@"Score_Valaue" forKey:@"player2-Score"];

//For Round1
[mutArrayRound insertObject:mutDic atIndex:0];

//For Round2
[mutArrayRound insertObject:mutDic atIndex:1];


/*
    You can access for particular round using mutDic=[mutArrayRound objectAtIndex:0];
    And to access player score, you can use key score=[mutDic valueForKey:@"Player1_Score"];
 */

[mutArrayRound release];
[mutDic release];
2 голосов
/ 02 апреля 2012

Вы можете сделать NSMutableArray из NSDictionary:

      NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:10];
                // Now say Player one got 50 and Player2 got 65 in first round then add them in dictionary


                NSDictionary *dict  = [[NSDictionary alloc] initWithObjectsAndKeys:@"50",@"P1",@"65",@"P2", nil];
                [arr addObject:dict];
[dict release];


            // As soon as you got the sores make a NSDictionary object and init it with objects like above and add that to the mutable array . It will add it to next index.

Надеюсь, это поможет.

1 голос
/ 02 апреля 2012

Идея 1:

NSMutableDictionary* playerArounds = [NSMutableDictionary dictionary];
NSMutableDictionary* playerBrounds = [NSMutableDictionary dictionary];

[playerArounds setObject:@"5" forKey:@"1"]; 
// Player A scored 5 for round 1

// etc...

Идея 2: (подходит, если> 2 игрока)

NSMutableArray* playerRounds = [NSMutableArray arrayWithObjects:nil];

for (int i=0; i<10; i++)
    [playerRounds addObject:[NSMutableDictionary dictionary]];

[[playerRounds objectAtIndex:0] setObject:@"5" forKey:@"1"];  
// Player 0 scored 5 for round 1

// etc...

Идея3: (более чистый подход C)

// a 2-dimensional array
int scores[2][10]; 

scores[0][2] = 5;

// Player 0's score for round 3 (2+1) is 5

Как указано:

Вместо, например,[playerArounds setObject:@"5" forKey:@"1"];, поскольку ваши значения будут целыми (а не строковыми), вам лучше использовать (это более разумно):

например, [playerArounds setObject:[NSNumber numberWithInt:5] forKey:[NSNumber numberWithInt:1]];

...