【问题标题】:Memory Management example内存管理示例
【发布时间】:2010-09-15 04:33:43
【问题描述】:

这是我的一个课程中的一些代码,我想知道我是在正确处理内存还是在任何地方泄漏?

@implementation CardViewController
@synthesize playerImage;
@synthesize cardLabel;
@synthesize card;
@synthesize frontView;
@synthesize backView;
@synthesize nameLabel;
@synthesize infoLabel;
@synthesize delegate;

-(void) initialiseButtons 
{
NSLog(@"initialiseButtons  %d",totalButtons);
int ypos = playerImage.frame.origin.y + playerImage.frame.size.height + 42;
for(int i=0; i<totalButtons; i++) 
{       
    StatView *sv = [[StatView alloc] initWithYPos:ypos];
    sv.tag = 100 + i;
    [sv.overlayButton addTarget:self action:@selector(statTapped:)    
                 forControlEvents:UIControlEventTouchUpInside];
    sv.overlayButton.tag = 10 + i;
    [self.frontView addSubview:sv];
    ypos += 26;
}
}

-(IBAction) statTapped:(id) sender 
{

UIButton *tappedButton = (UIButton *)sender;
int tag = tappedButton.tag;
if(delegate && [delegate respondsToSelector:@selector(cardTapped:)]) {
    [delegate cardTapped:tag-10];
}
 }

-(void) viewDidLoad 
{
NSLog(@" viewDidLoad CVC");
[self initialiseButtons];

metaData = [[NSArray alloc]     
      initWithObjects:@"Height",@"Weight",@"Games",@"Attack",@"Defense", nil];
 }

-(void) setCard:(Card *)newCard 
{
NSLog(@"setCard");
[card release];
card = [newCard retain];
[self updateUI];
}

- (void)dealloc 
{
[card autorelease];
[metaData autorelease];
 [super dealloc];
}

@end

我应该在哪里释放 StatView *sv = [[StatView alloc] initWithYPos:ypos]; 如果我在每个循环中释放它不会导致问题吗? 除此之外,我还能处理剩下的内存吗?

谢谢 -代码

【问题讨论】:

  • 是否有可以在帖子中使用的标签,以便我发布的代码的 sn-ps 显示得很好?
  • 是的 - 指示在您输入问题的位置。使用四个空格或 101010 按钮。

标签: iphone objective-c


【解决方案1】:

是的,您应该在每次循环迭代结束时释放该 StatView,将其插入到视图层次结构中。

【讨论】:

    【解决方案2】:

    您应该尝试 XCode 中内置的分析器,因为它非常擅长发现这些类型的内存泄漏。有一个look

    【讨论】:

      【解决方案3】:
      1. 在此行之后释放新的StatView

        [self.frontView addSubview:sv];

        [sv release]; // frontView retains sv

      2. 释放在dealloc 中声明为retaincopy 的所有属性。候选属性:playerImage、cardLabel 等。发送release 消息,而不是autorelease

        \\[card autorelease];

        [card release];

      3. viewDidUnload 中释放所有声明为IBOutlet 的属性并将变量设置为nil

        [frontView release], frontView = nil;

      【讨论】:

      • 候选属性是什么意思:?
      • 我猜的属性被保留了。
      【解决方案4】:

      您应该在将它添加到视图层次结构后立即释放它(通过发送 addSubview: 并将新分配的视图作为参数)。这是因为 UIView 对象保留了它们的子视图。

      我注意到另一个问题:您的 setCard 方法应该首先检查新卡和旧卡是否相同,在这种情况下什么也不做。否则,您可能会释放您现有的卡,然后再次尝试保留它,却发现它已被释放。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-23
        • 2016-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-31
        • 2011-05-15
        • 2022-09-27
        相关资源
        最近更新 更多