iphone - 如何释放 iPhone 中已声明对象的内存

标签 iphone ios objective-c memory-management

<分区>

我遇到了一个小问题,

我在 .h 文件中声明了一个数组,并在 viewDodLoad 方法中分配了它。在 dealloc 方法中,我检查数组是否不等于 nil 然后 array=nil。但它在 iOS 5.1.1 中崩溃了。我不明白这次崩溃的原因。

我的代码,

   @interface SampleApp : UIViewController
   {
        NSMutableArray *objArray;
   }
   @end

   @implementation SampleApp

   - (void)viewDidLoad
   {
        [super viewDidLoad]; 
        objArray=[[NSMutableArray alloc]init];
   }
   -(void)dealloc
   {
      [super dealloc];
      if (objArray!=nil)
     {
         [objArray removeAllObjects];
         [objArray release];objArray=nil;
     }
  }

最佳答案

dealloc 方法的末尾添加 [super dealloc]; 而不是在开头。 Apple 在其 documentation for dealloc method 中推荐.

When not using ARC, your implementation of dealloc must invoke the superclass’s implementation as its last instruction.

如下修改代码,

   -(void)dealloc
   {
      if (objArray!=nil)
     {
         [objArray removeAllObjects];
         [objArray release];objArray=nil;
     }
      [super dealloc];
   }

此外,在释放整个数组时,您无需调用 [objArray removeAllObjects]。当数组被释放时,它会在内部对所有包含的对象调用 release

希望对您有所帮助!

关于iphone - 如何释放 iPhone 中已声明对象的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18438090/

相关文章:

javascript - 软键盘可见时无法单击按钮

ios - 如何正确地将 NSNumber 转换为 long long int?

objective-c - 两个类之间的 IBOutlets 属性不保留。解除分配?

iphone - 自定义键盘为 iPhone sdk 中的应用程序制作?

ios - 具有多个 View 的 UIPageViewController

iphone - 哪种声音格式最适合cocos2d游戏项目?

iphone - UIImage 只拉伸(stretch)一部分

方向更改后 iOS ViewController 布局不正确

iphone - 如何通过 iOS 中的 `null` 解释器对 `json` 对象进行错误检查

ios - NSMutableDictionary setValue :forUndefinedKey