Question

Allocating a custom class in a vc. Then I set a bool value (either set or . notation). The value never gets to the custom class - always reports NO.

Googled and tried many different variations - none work. What else could be wrong with the code below?

CustomView.h

    @interface CustomView : UIScrollView <UIScrollViewDelegate> {
    BOOL myLocalProperty;
}

@property (assign) BOOL myProperty;

CustomView.m

     @implementation CustomView

    @synthesize myProperty =_myProperty;

    - (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];

    myLocalProperty = _myProperty;

    if (myLocalProperty==YES) {
        NSLog(@"YES");
    } else if (myLocalProperty==NO) {
        NSLog(@"NO");
    }

    return self;
}

ViewController.m (in some method that is def. being called)

CustomView *myView = [[CustomView alloc] initWithFrame:CGRectZero];

    myView.myProperty=YES;

This value of YES never gets to the property. Anything obviously wrong here?

Was it helpful?

Solution

The value of YES does get there, but that happens after you have printed the default NO.

The current value of _myProperty is printed in the initializer; by the time you assign the property YES, the initializer is done!

You can check that the value does get there by adding a method to show the current value of the property:

- (id)showMyProperty {
    myLocalProperty = _myProperty;
    if (myLocalProperty==YES) {
        NSLog(@"YES");
    } else if (myLocalProperty==NO) {
        NSLog(@"NO");
    }
}

Now change your code that creates CustomView as follows:

CustomView *myView = [[CustomView alloc] initWithFrame:CGRectZero];
myView.myProperty=YES;
[myView showMyProperty]; // This should produce a "YES" in NSLog

OTHER TIPS

You're logging the value of myProperty in CustomView's initWithFrame: method, but you're not assigning YES to myProperty until initWithFrame: has returned. You should try logging NSLog("myView.myProperty = %@", myView.myProperty ? @"YES" : @"NO"); after your assignment, myView.myProperty = YES;.

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