views:

200

answers:

2

Just beginning with iPhone development i seem to miss something fundamental.

In a View based application i'm adding programaticaly a UIView subclass in the ViewController implementation file and can set a value:

- (void)viewDidLoad {

    [super viewDidLoad];

 CGRect myRect = CGRectMake(20, 50, 250, 320);

 GraphView *graphView = [[GraphView alloc] initWithFrame:myRect];

 [self.view addSubview:graphView];

    graphView.myString = @"Working here";

}

When i try to change the same value with an action in the same file, the Build fails because graphView is undeclared:

- (void)puschButton1 {


 graphView.myString = @"Not working here";

}

Because I use a UIView subclass there is no outlet for my GraphView instance.

How can i get a reference to my subview? Or should this be done in another way?

Thanks in advance

Frank

A: 

You could store graphView as a class variable.

EDIT: note that addSubview will increase the retain count of the object, somewhere in your class you will need to balance the alloc with a release and the addSubview with a removeFromSuperview or a release.

Sam
A: 

The easiest solution is to make graphView an instance variable for your view controller, instead of declaring it in viewDidLoad.

Put something like this in your .h file:

@class GraphView;

@interface MyViewController : UIViewController {
    GraphView *graphView;
}

// ... method declarations ...

@end

If you don't want to do that, another way is to set graphView's tag property, and then call the superview's viewWithTag: method to retrieve the view when you need it.

I'm not sure what you mean by "Because I use a UIView subclass there is no outlet for my GraphView instance." You generally declare outlets on your controller class, and it doesn't matter whether you are using a subclass of UIView.

As an aside, I'll note that you should probably release that GraphView at some point, or you'll have a memory leak.

Kristopher Johnson
Thanks for the fast answer! The Compiler complains with:warning: local declaration of 'graphView' hides instance variablewith the addSubview Statement.
Frank Martin
That's because you still have this line: "GraphView *graphView = [[GraphView alloc] initWithFrame:myRect];" Change it to: self.graphView = [[GraphView alloc] initWithFrame:myRect];
David Wong
David, you made my day! :-) THAT was the fundamental thing i was missing! Thanks a lot Kristopher, David and Sam.
Frank Martin