1 Replies - 3081 Views - Last Post: 16 August 2013 - 12:27 PM

#1 Zag  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 20-July 13

(Noob) Problem with Deck of Cards Class

Posted 02 August 2013 - 03:04 AM

Hi.

I'm trying to create a class called DeckOfCards that I can use for future programs.
So far, I'm just experimenting with loading an NSMutableArray with random numbers (1-52)
and printing them out (NSLog).

The problem is that all values in the array are showing "null".

What am I doing wrong?

Note: I'm new to programming and I'm sure there are more efficient ways to create a deck of cards.
I'm just using this exercise to check if I understand NSMutableArrays and NSNumbers.

Thanks!

.h
#import <Foundation/Foundation.h>

@interface DeckOfCards : NSObject {
    NSMutableArray *deck;
    NSNumber *randNum;
}

-(void) createDeck;
-(void) print;

@end




.m
#import "DeckOfCards.h"

@implementation DeckOfCards

-(void) createDeck {
    for (int i=0; i<52; i++) {
        randNum = [NSNumber numberWithInt: (arc4random()%52)+1];
        [deck addObject: randNum];
    }
}

-(void) print {
    for (int i=0; i<52; i++) {
        NSLog(@"%@", [deck objectAtIndex:i]);
    }
}
@end




main
#import <Foundation/Foundation.h>
#import "DeckOfCards.h"

int main(int argc, const char * argv[]) {

    @autoreleasepool {
        
        DeckOfCards *myDeck = [[DeckOfCards alloc]init];
        [myDeck createDeck];
        [myDeck print];
    }
    return 0;
}


Is This A Good Question/Topic? 0
  • +

Replies To: (Noob) Problem with Deck of Cards Class

#2 SegFaulty  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 14
  • View blog
  • Posts: 35
  • Joined: 11-October 10

Re: (Noob) Problem with Deck of Cards Class

Posted 16 August 2013 - 12:27 PM

My guess is because you are not initializing the array that holds the deck. Try creating your init method:

- (id)init{
    deck = [[NSMutableArray alloc] init];
}




That should fix it.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1