Objective C 方法中的实例变量初始化

发布于 2024-11-17 07:23:53 字数 488 浏览 2 评论 0原文

有人遇到这个问题吗? 如果我需要一个实例变量,而不是作为属性,并在方法中初始化该变量,那么当我需要它时,它已经被释放了。自动释放的对象会发生这种情况。这是什么原因呢?

通常实例变量应该具有类对象的整个生命周期。但似乎如果该变量是函数的局部变量,并且它是一个自动释放对象,那么它会在函数退出时被释放。

MyClass.h

@interface MyClass:UIViewController {
  NSDate * date;
}

MyClass.m

@implementation MyClass {

- (void) anInit {
  date = [NSDate date];
}

- (void) useDate {
  NSLog (@"%@", date); 
// here date is already release, and get bad access.
}

}

Did any body get this issue?
If I need an instance variable, not as a property, and initialize this variable in a method, then when I need it, it is already released. It happens for autoreleased objects. What is the reason for this?

Usually instance variable should have the whole lifetime of the class object. But it seems if the variable is local to a function, and its a autorelease object, it is released when the function exits.

MyClass.h

@interface MyClass:UIViewController {
  NSDate * date;
}

MyClass.m

@implementation MyClass {

- (void) anInit {
  date = [NSDate date];
}

- (void) useDate {
  NSLog (@"%@", date); 
// here date is already release, and get bad access.
}

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

哭了丶谁疼 2024-11-24 07:23:53

您需要保留日期。

当自动释放池下次耗尽时,自动释放的对象将被释放。发生这种情况与对象的生命周期无关。

您的实现应该如下所示:

@implementation MyClass {

    - (void) anInit {
      date = [[NSDate date] retain];  // or [[NSDate alloc] init]
    }

    - (void) useDate {
      NSLog (@"%@", date); 
    }

    - (void) dealloc {
        [date release];
        [super dealloc];
    }

}

You need to retain date.

An autoreleased object will be released when the autorelease pool is next drained. When this happens has nothing to do with the lifecycle of your object.

Your implementation should look like this:

@implementation MyClass {

    - (void) anInit {
      date = [[NSDate date] retain];  // or [[NSDate alloc] init]
    }

    - (void) useDate {
      NSLog (@"%@", date); 
    }

    - (void) dealloc {
        [date release];
        [super dealloc];
    }

}
二智少女猫性小仙女 2024-11-24 07:23:53

[NSDate date]便捷构造函数并且是自动释放的,需要添加retain调用。还要确保 anInit 仅被调用一次,否则您将在不先调用 [date release] 的情况下造成内存泄漏。

- (void) anInit {
  date = [[NSDate date] retain];
}

[NSDate date] is a Convenience Constructor and is autoreleased, you need to add a retain call. Also make sure anInit is only called once or you will create a memory leak without calling [date release] first.

- (void) anInit {
  date = [[NSDate date] retain];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文