문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top