0

刚开始 iPhone 开发,我似乎错过了一些基本的东西。

在基于视图的应用程序中,我在 ViewController 实现文件中添加了一个 UIView 子类,并且可以设置一个值:

- (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";

}

当我尝试使用同一文件中的操作更改相同的值时,构建失败,因为未声明 graphView:

- (void)puschButton1 {


 graphView.myString = @"Not working here";

}

因为我使用 UIView 子类,所以我的 GraphView 实例没有出口。

如何获得对我的子视图的引用?还是应该以其他方式完成?

提前致谢

坦率

4

2 回答 2

0

您可以存储graphView为类变量。

编辑:请注意,这addSubview将增加对象的保留计数,在您的班级某处,您需要平衡allocareleaseaddSubviewaremoveFromSuperview或 a release

于 2010-02-14T22:24:15.690 回答
0

最简单的解决方案是graphView为您的视图控制器创建一个实例变量,而不是在viewDidLoad.

.h在你的文件中放这样的东西:

@class GraphView;

@interface MyViewController : UIViewController {
    GraphView *graphView;
}

// ... method declarations ...

@end

如果不想这样做,另一种方法是设置graphView'tag属性,然后viewWithTag:在需要时调用 superview 的方法来检索视图。

我不确定“因为我使用 UIView 子类,所以我的 GraphView 实例没有出口”是什么意思。您通常在控制器类上声明插座,无论您是否使用UIView.

顺便说一句,我会注意到你可能release应该GraphView在某个时候这样做,否则你会有内存泄漏。

于 2010-02-14T22:24:36.523 回答