5

I have a subclass of an UIImageView with some boolean properties as follows: And I cannot set the isOccupied value to YES in my code.

#import <UIKit/UIKit.h>

@interface TargetView : UIImageView

@property (strong, nonatomic) NSString* letter;
@property (assign, nonatomic) BOOL isMatched;
@property (assign) BOOL isOccupied;

-(instancetype) initWithLetter:(NSString*) letter andSideLength:(float)sideLength;

@end

Each of these TargetViews are stored in NSMutableArray* _targets;

And when I execute the following

   for (TargetView* tv in _targets) {
        if (!tv.isOccupied) {
            tv.isOccupied = YES;
           //[tv setIsOccupied:YES]; <--- have also tried used this setter
            break;
        }
    }

The targetView is still evaluating as False the next time I run the code. So I am not able to set the isOccupied value to TRUE, true or YES.

I initialise the targetView as follows, and all targetViews are initially set to isOccupied is false

-(instancetype)initWithLetter:(NSString *)letter andSideLength:(float)sideLength{
UIImage* img = [UIImage imageNamed:@"blank.png"];
self = [super initWithImage:img];

if (self != nil) {
    self.isMatched = NO;
    self.isOccupied = NO;

    float scale = sideLength/img.size.width;
    self.frame = CGRectMake(0, 0, img.size.width*scale, img.size.width*scale);

    _letter = @"";
}
return self;

}

The code that is assigning the boolean value to the targetView is delegate method running in the controller and not within the targetView class itself. Could this be causing the problem? Or is it how I have set up my properties? I've tried assign, atomic, nonatomic, ......

EDIT**

I changed some to the code to use **_isOccupied** instead of **self.isOccupied** in the class initialisation. and now it works. Can anyone explain why this works?

Linda Keating
  • 2,215
  • 7
  • 31
  • 63
  • 1
    Possible duplicate http://stackoverflow.com/questions/4864239/using-a-bool-property or http://stackoverflow.com/questions/8482444/correct-way-of-setting-a-bool-property – Paulo Sep 01 '15 at 00:36

1 Answers1

5

You are setting self.isOccupied during the initialization of self.

Self is not fully initialized yet and you are trying to use a property of it. Obviously the property is not initialized yet.

The property self.isOccupied is backed up by a local variable ("ivar") called _isOccupied. Every time you store something on self.isOccupied, iOS is storing the value on _isOccupied.

iOS will accept using that iVar directly because that is already initialized.

BTW, Apple suggests you to use the following syntax when you use "is" on a property:

@property (nonatomic, assign, getter=isOccupied) BOOL occupied;

then you can use image.occupied = YES to set and [image isOccupied]; to get.

Duck
  • 34,902
  • 47
  • 248
  • 470