Question

I have a subclass of NSObject. In this class I have an NSUInteger declared like this:

@interface Deck : NSObject

- (id)initDecks:(NSUInteger)decks;
- (Card *)drawCard;

@property (nonatomic, assign) NSUInteger drawnCards;

In my implementation file, I have the following code:

#import "Deck.h"

@implementation Deck

- (id)initDecks:(NSUInteger)decks {
    self = [super init];

    if (self) {
        self.drawnCards = 1;
    }

    return self;
}

- (BJCard *)drawCard {
    self.drawnCards++;
    return nil;
}

The number assigned to the NSUInteger (drawnCards) in the init method is set correctly, however, I am not able to change it later. I get no warnings or crashes in Xcode, but the number remains unchangeable. I have tried to do self.drawnCards++ and self.drawnCards = 10 etc, but nothing works. Any idea what might be wrong with my code? I am checking the value with:

NSLog(@"Value: %tu", self.drawnCards);
Was it helpful?

Solution

I believe the problem here is the objectiveC dot syntax. Because you are doing . with an object this is the equivalent to doing [self drawnCards]++ method call. The result of the method is incremented, not the drawnCards ivar. To do what you want you'll either need to do _drawnCards++ (access the iVar directly), or you'll need to do [self setDrawnCards:self.drawnCards++].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top