动态对象创建和发布

时间:2009-09-04 16:53:47

标签: iphone objective-c memory-management

我有一个类来实例化其他一些类。它正在努力控制它们的生命周期,或者应该;)一个管理其他包含事件的根类,并且是根视图的子视图。

每个视图都涉及很多图形,需要在加载下一个图像之前清除它们。

知道如何卸载当前子视图以及如何加载下一个子视图,同时在“触及结束”方法中保持对事件处理使用的命名引用?

由于 //:)

1 个答案:

答案 0 :(得分:0)

假设您要转储旧的子视图并保留新的子视图,这实际上非常简单。你想要这样的东西:

@interface YourView : UIView
{
    // Create an ivar in your class
    UIView *_subview;
}

// Propertize it as retain to take care of most of the heavy lifting
@property(nonatomic, retain) UIView *subview;

@end


@implementation YourView

// Map the ivar to the property
@synthesize subview = _subview;

// Call this to put in a new subview
-(void) switchToNewSubview:(UIView*)newSubview
{
    // Remove the old subview, set the new one, and if the new one isn't nil
    // add it as a subview
    [self.subview removeFromSuperview];
    self.subview = newSubview;
    if(newSubview)
        [self addSubview:self.subview];
}

// Don't forget to nil out the subview on dealloc to release it
-(void) dealloc
{
    self.subview = nil;
    [super dealloc];
}

@end