【问题标题】:Releasing view object释放视图对象
【发布时间】:2011-03-17 03:30:40
【问题描述】:

只是想知道为什么我在构建这个时会在 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 时出现相同的错误。

【问题讨论】:

    标签: iphone objective-c uiview dealloc


    【解决方案1】:

    因为“baseView”没有在 .h 文件中声明,所以我猜。指针只存在于声明它的方法的生命周期内。

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

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

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

    【讨论】:

      【解决方案2】:

      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
      

      【讨论】:

        【解决方案3】:

        尝试使用

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

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

        【讨论】:

          【解决方案4】:

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

          【讨论】:

          • 在这种情况下,该方法是“viewDidLoad”。所以它才会被认为是该方法的本地方法,然后才正确?
          • 是的,所以不能在 dealloc 中访问
          猜你喜欢
          • 1970-01-01
          • 2011-11-18
          • 2011-07-15
          • 2015-09-25
          • 2012-09-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多