Objective-c – Objective C makes integer from pointer without a cast passing objects as args


I'm trying to make blackjack in objective C, and am having trouble passing objects around. My Hand class basically takes a deck and draws cards from it, adding them to an array.

Here's the Hand methods involved:

- (id)init : (Deck*) deck
    [self draw: deck];
    [self draw: deck];
    return self;

- (void)draw: (Deck*)deck;
    Card* C= [deck drawFromDeck];
    [cards addObject: C];

Here's the problematic part of main:

Deck* deck=[[Deck alloc] init];
Hand* hand=[[Hand alloc] init: deck ];

The second line of that gets the "integer from pointer without a cast" error. Whenever I run the code, the hand never has cards in it because there's no deck to draw from (I think 🙂 ). Do I need to pass or parse the Deck* differently? (if you need me to post any more code, just ask)

Thanks guys!! 😀

Edit with regards to bounty: Although I do believe the answer I accepted is well explained and , this question has gotten an average of over 17 views a day for the past year and a half. This means that this question is probably the first experience many people have with stackoverflow, and improving it will not only show us in a better light, it will probably save a lot of people's time. While it has good answers now, I want to make sure that it is as perfect as possible, especially because we don't really know how many of those people were able to follow it and solve their problem.

Go ahead and submit edits to the existing answers or add your own. (Mods, do you think this would be a good candidate for community wiki?)

Best Solution

The problem, based on the extra code you've posted below, is that you have two methods with the same name but whose parameters don't match, namely - (id)init: (Deck*)deck and - (id)init: (int)newvalue.

Normally this isn't a problem, but in this case the types are structurally different - a pointer and an int. The compiler can distinguish which you mean based on the type of the receiver, but this only works when it has its static type. For example, if you had:

Hand *h = [Hand alloc];
h = [h init: deck];

It would stop giving you a warning. This is very unusual code, though - alloc and init almost always go on the same line.

Since alloc returns an id, and not a Hand it doesn't know that the init call in [[Hand alloc] init:deck] is to a Hand, and not a Card. See Apple's Docs on static typing for more information about that.

The easiest (and a reasonable) solution is to rename the methods to indicate the type of the argument. For example, you could use initWithCardValue: and initWithDeck:.

EDIT: Also, yes, heed the suggestions from the other posts about the proper behavior inside the init method. (It's not causing the warning, but it may be causing the segfault.)

Related Question