【发布时间】:2012-04-07 17:59:32
【问题描述】:
有人可以帮我写下面的代码吗?在这个循环中随机获取 EXC_BAD_ACCESS。我猜 [NSString stringWithFormat:....] 有问题,但不明白为什么,也不知道如何解决。非常感谢。
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
CGRect tileFrame=CGRectMake(i*tileSize, j*tileSize, tileSize, tileSize );
UILabel * t=[[UILabel alloc]initWithFrame:tileFrame];
t.text=[NSString stringWithFormat:@"%i",j*row+i];
///If there is a crashing ,it always stop at here, right after the [NSString stringWithFormat:.....]
t.backgroundColor=[UIColor clearColor];
//NSString * temps=[NSString stringWithFormat:@"%i",j*row+i ];
//t.text=temps;
[myView addSubview:t];
[t release];
}
}
顺便说一句,我在网上阅读了一些帖子,有人告诉我按照以下方式进行操作可以解决问题。我不确定这一点,当这个对象仍在其范围内时,为什么需要保留一个自动释放对象。更重要的是我不应该在某处释放保留对象吗?否则会导致内存泄漏。
替换
t.text=[NSString stringWithFormat:@"%i",j*row+i];
与:
NSString * temps=[NSString stringWithFormat:@"%i",j*row+i ];
[temps retain];
t.text=temps;
【问题讨论】:
-
到底是哪里崩溃了?没有崩溃日志,任何人都很难说出答案。
-
那个疯狂的双 for 循环可能与它有关。
-
这种“疯狂”的双重 for 循环被用于数以万计的应用程序中。如果你做一些涉及列和行的事情,这实际上是非常标准的。 m)
-
我很确定您的应用不会因为这段代码而崩溃。
-
正如@MatthiasBauch 所说,这不是您崩溃的根源。
标签: objective-c cocoa-touch nsstring autorelease stringwithformat