简体   繁体   中英

Assign value to NSUInteger in object after init

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);

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++] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM