0

只是想知道为什么我在构建这个时会在 dealloc 中得到“baseView”未声明的错误。

CGRect baseFrame = CGRectMake(0, 0, 320, 480);
UIView *baseView = [[UIView alloc] initWithFrame:baseFrame];
self.view = baseView;

- (void)dealloc {
[baseView release];
[super dealloc];

}

我使用 alloc 创建了视图,我不确定为什么在尝试释放 baseView 时会出现错误。(尝试在 viewDidUnload 中将其设置为 nil 时出现相同的错误。

4

4 回答 4

2

因为“baseView”没有在 .h 文件中声明是我的猜测。指针仅在声明它的方法的生命周期内存在。

您可以按如下方式解决此问题:

CGRect baseFrame = CGRectMake(0, 0, 320, 480);
UIView *baseView = [[UIView alloc] initWithFrame:baseFrame];
[self.view addSubview:baseView];
[baseView release];

该视图将保留 baseView,因此您可以继续在此处释放它。然后删除中的引用dealloc

于 2011-03-17T03:35:45.220 回答
1

指针在您创建它的任何方法中都在baseView本地声明。如果您也需要baseView在其他方法中使用,我建议您将其添加为实例变量。

// MyClass.h
@interface MyClass {
    UIView *baseView; // declare as an instance variable;
}

@end

// MyClass.m
#import "MyClass.h"

@implementation MyClass

- (void)someMethod {
    baseView = [[UIView alloc] initWithFrame:..];
}

- (void)someOtherMethod {
    // baseView is accessible here
}

- (void)yetAnotherMethod {
    // baseView is accessible here too
}

@end
于 2011-03-17T03:38:07.103 回答
0

尝试使用

[self.view addSubView:baseView];
[baseView release];

如果你想从 dealloc 释放,你需要在 .h 文件中声明

于 2011-03-17T03:36:18.683 回答
0

baseView被声明为局部变量并且是已知的或只能通过声明它的方法访问。如果必须由类的其他方法访问它,请确保baseView将其声明为实例变量。

于 2011-03-17T04:28:18.377 回答