开发者

Releasing view object

Just wondering why I'm getting the 'baseView' undeclared error in dealloc when building this.

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

- (void)dealloc {
[ba开发者_Python百科seView release];
[super dealloc];

}

I created the view with an alloc, I'm not sure why I'm getting the error when trying to release baseView. (I get the same error when trying to set it to nil in viewDidUnload.


Because "baseView" is not declared in the .h file would be my guess. The pointer only exists for the life cycle of the method in which it's declared.

You can fix this as follows:

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

The view will retain the baseView, so you can go ahead and release it here. Then remove the reference in dealloc.


The baseView pointer is declared locally in whatever method you are creating it in. If you need to play around with baseView in other methods too, I suggest you add it as an instance variable.

// 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


try to use with

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

If you want to release from dealloc , you need to declare in .h file


baseView is declared as a local variable and is known or can be accessed only by the method in which it is declared. If it has to be accessed by other methods of the class make sure baseView is declared as an instance variable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜