Search code examples
iphoneiosuiviewuiviewcontrollerios4

How can UIView access property of UIViewController?


There is a UIViewController, it has an instance variable of NSInteger. I declare it in the UIViewController.h file as:

NSInterger *theNum;
...
@property NSInteger *theNum;

Then, I synthesize it in its .m file:

@synthesize theNum;

The view (UIView) of this UIViewController has a method doSomething that needs to access the value of theNum.

Here is the code in this "view"'s .m file:

-(void)doSomething {

NSInteger *myNum = self.superview.theNum; //error: request for member 'theNum' in something not a structure or union

// do something

}

So, how can I get the value of theNum from UIViewController to its UIView?


Solution

  • You will need to pass the number from the UIViewController to the UIView. The controller should know about the view and not the other way around.

    //SomeView.h
    @interface SomeView : UIView
    NSInteger theNum; 
    //You have NSInteger *theNum. I am guessing you made that a pointer by accident
    }
    
    @property(assign) NSInteger theNum;
    
    @end
    
    //SomeViewController.m
    
    -(void)viewDidLoad
    {
       [super viewDidLoad];
       ((SomeView*)self.view).theNum = theNum;//This theNum belongs to the ViewController
    }