【问题标题】:Memory leak in a small code with dealloc使用 dealloc 的小代码中的内存泄漏
【发布时间】:2010-10-29 09:32:29
【问题描述】:

请帮助我,这段代码正确吗?我的意思是,我们真的需要在这个类中使用 dealloc 方法吗,为什么需要或不需要呢?如果我们在这里不使用 dealloc 会不会是内存泄漏? 谢谢!

    #import <Foundation/Foundation.h>


@interface MyData : NSObject
{
    @private
    NSString *name;
    NSString *surname;
    NSString *email;
    NSString *telephone;
    UIImage *image;
}

@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *surname;
@property (nonatomic, retain) NSString *email;
@property (nonatomic, retain) NSString *telephone;
@property (nonatomic, retain) UIImage *image;
@end

#import "MyData.h"


@implementation MyData

@synthesize name;
@synthesize surname;
@synthesize email;
@synthesize telephone;
@synthesize image;

- (void) dealloc
{
    [name release];
    [surname release];
    [email release];
    [telephone release];
    [image release];    

    [super dealloc];    
}
@end

【问题讨论】:

  • 出于好奇,这是干什么用的?
  • 我只是这个领域的新人,我想知道现在谁支持所有这些记忆的东西))

标签: objective-c ios4 release dealloc


【解决方案1】:

代码是正确的,是的,如果你没有dealloc,就会有内存泄漏。

如果您设置姓氏或电子邮件,则保留该字符串。然后可以释放 MyData 实例,并且没有 dealloc 姓氏,或者电子邮件字符串仍然存在,但现在您无法引用它 - 泄漏。

【讨论】:

    【解决方案2】:

    请再次说明您的问题。您只是要声明对象吗?如果你这样做,你不需要释放它们。如果您要在类的任何部分声明并分配它们的内存,您将需要使用 dealloc 方法来释放内存。

    所以要小心内存管理,因为如果你不释放它们,它会提供内存泄漏,如果你要释放或释放任何对象而不分配内存,它会让你的应用程序崩溃。

    【讨论】:

    • 那么你应该使用dealloc方法来释放对象占用的内存。这将有助于防止内存泄漏。您的代码方向正确。
    猜你喜欢
    • 2012-06-17
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多