【问题标题】:How to debug memory allocation issues?如何调试内存分配问题?
【发布时间】:2010-06-09 15:17:48
【问题描述】:

我正在编写一个 iPhone 应用程序,当用户单击 UITableView 中的一个元素时,它试图创建第二个视图。代码看起来像

  ReplyToViewController *reply = [[ReplyToViewController alloc] initWithNibName:@"ReplyTo" bundle:nil];
 reply.delegate = self;
 Message *message = [resultData objectAtIndex:indexPath.row];
 int dbid = [message.bizid intValue];
 NSLog(@"dbid=%d",dbid);

 reply.currentMessage = message;
 reply.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
 [self presentModalViewController:reply animated:YES];

回复对象被正确创建并且视图正确。上面代码段的最后一行调用了一些框架代码,最终调用了ReplyToViewController的viewDidLoad方法。上面代码中回复对象的地址和viewDidLoad中对象的地址不一样。

知道这个新对象是从哪里来的吗?我该如何调试?我还在ReplyToViewController 中添加了以下方法的init 方法,希望它会被调用并且我可以找到谁在创建这个新对象。但它并不止于此方法。

任何帮助将不胜感激。

- (id) init
{ 
 /* first initialize the base class */
    self = [super init]; 
 return self;
}

// Following gets called from the 1st code segment.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) 
 {
        // Custom initialization
    }

    return self;
}

- (void)viewDidLoad 
{
    [super viewDidLoad];
    NSLog(currentMessage.text]; // THIS returns nil and the program fails later in the code.
}

【问题讨论】:

    标签: iphone memory-leaks viewcontroller


    【解决方案1】:

    我确定这是无关的,但我认为:

    NSLog(currentMessage.text];
    

    应该是这样的:

    NSLog(currentMessage.text);
    

    另外,我发现分析 (Cmd+Shift+A) 我的代码总是有助于追踪潜在的内存泄漏并防止过度的内存分配。

    【讨论】:

      【解决方案2】:

      最可能的解释是报告错误。

      通常当人们看到一个对象的不同地址时,这是因为他们在日志语句中使用了错误的格式描述符。

      一个常见的错误是:

      NSLog(@"Object address=%i", myObject); // any numerical formatter %d,%f...
      

      ... 产生一个随机数。你真的想要:

      NSLog(@"Object address=%%qX",&myObject);
      

      ... 以十六进制转储地址。

      另一个错误是:

      NSLog(@"Object address=%%qX",&[myObject description]); 
      

      ... 返回每次更改的描述字符串的地址。

      还有其他的,但你明白了。

      如果您使用日志语句,请检查调试器中的地址以确认它是不同的对象。

      不相关,但我会摆脱类的初始化方法,因为它们除了调用 super 之外什么都不做。如果您不自定义,您不妨让编译器默认为超级。

      【讨论】:

        猜你喜欢
        • 2010-10-21
        • 1970-01-01
        • 1970-01-01
        • 2011-01-07
        • 2011-03-18
        • 2012-07-14
        相关资源
        最近更新 更多