如何管理对象的内存

时间:2022-12-27 21:22:09
@interface MyClass : NSObject {
    MyObject *objecto;
}

I have an object that I declare as a private variable (I think this is how you do a private variable in objective c).

我有一个对象,我声明为一个私有变量(我认为这是你在目标c中做私有变量的方式)。

Do I have to retain and release it?

我必须保留并释放它吗?

For example if I have a function should I be retaining it as soon as it has been assigned? Should I be using properties to do this always?

例如,如果我有一个功能,我应该在分配后立即保留它吗?我应该一直使用属性吗?

initWithMyObject: MyObject *input

3 个解决方案

#1


2  

would suggest to read memory management guide ...

建议阅读内存管理指南...

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html

#2


1  

Four Basic Rules To Allocate and Release Memory

分配和释放内存的四个基本规则

  1. If you own it, release it.

    如果您拥有它,请将其释放。

  2. If you don’t own it, don’t release it.

    如果您不拥有它,请不要将其释放。

  3. Override dealloc in your classes to release the fields that you own.

    覆盖类中的dealloc以释放您拥有的字段。

  4. Never call dealloc directly.

    永远不要直接打电话给dealloc。

#3


0  

You are going to create objecto (alloc/init) in your init method of MyClass. And release objecto in the dealloc of MyClass.

您将在MyClass的init方法中创建objecto(alloc / init)。并在MyClass的dealloc中释放objecto。

#1


2  

would suggest to read memory management guide ...

建议阅读内存管理指南...

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html

#2


1  

Four Basic Rules To Allocate and Release Memory

分配和释放内存的四个基本规则

  1. If you own it, release it.

    如果您拥有它,请将其释放。

  2. If you don’t own it, don’t release it.

    如果您不拥有它,请不要将其释放。

  3. Override dealloc in your classes to release the fields that you own.

    覆盖类中的dealloc以释放您拥有的字段。

  4. Never call dealloc directly.

    永远不要直接打电话给dealloc。

#3


0  

You are going to create objecto (alloc/init) in your init method of MyClass. And release objecto in the dealloc of MyClass.

您将在MyClass的init方法中创建objecto(alloc / init)。并在MyClass的dealloc中释放objecto。