我的第一篇文章发布到论坛,但我一直在使用过去几个月发布的答案,并找到非常有用的答案!我仍然在学习目标c并仍在学习一些基础知识。目的C:加载一系列图片时代码冻结
我的代码是几百行,所以我不想发布整个代码。代码的基本前提是将一系列随机图像加载到屏幕上的随机位置。
当我试图弄清楚如何处理这个想法时,我做了一个简单的测试版本,当按下按钮时会添加一个气球,然后当您弹出气球时删除所有创建的气球图像。
这个气球代码工作得很好,然后我把这个相同的概念添加到我的主代码。但是现在,当我仅使用更大的规模时,代码将冻结在99%cpu使用率和18.5 MB内存。代码永远不会失败,但会被冻结。较大的版本基本上只是在按下按钮而不是一个按钮时添加多个气球。有时多达15个图像。
是否有任何理由这种风格的代码不会在更大的规模上工作?或者当代码冻结并且没有给出错误时,如何解决问题。
.h文件中
@interface ViewController : UIViewController
{
// Holds an array of images of the balloons
NSMutableArray *BalloonArray;
// Holds an array file names of the balloon PNG files
NSMutableArray *BalloonNames;
}
-(void)AddBalloon:(id)sender;
-(void)PopBalloons:(id)sender;
@end
.m文件
@interface ViewController()
@end
@implementation ViewController
-(void)viewDidLoad
{
// Allocates memory for the array
BalloonArray = [[NSMutableArray alloc] init];
// Allocates memory and inputs the names of the images
BalloonNames = [NSMutableArray arrayWithObjects:[UIImage imageNamed:@"pink.png"],[UIImage imageNamed:@"blue.png"],[UIImage imageNamed:@"green.png"], nil];
[super viewDidLoad];
}
-(void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(void)AddBalloon:(id)sender
{
int x; // x position of the balloon image created
int y; // y position of the balloon image created
int i; // Random index value to pull a random balloon image out
// Random number generator for the x and y position
x = arc4random_uniform(230) + 30;
y = arc4random_uniform(400) + 150;
// Random index value from 0 to 2
// Random based on how many images there are to chose from
i = arc4random_uniform(3);
// Uses the image from the index value previously randomnized
UIImage *Balloon = [BalloonNames objectAtIndex:i];
// Places the UIImage in a UIImageView
UIImageView *BalloonView = [[UIImageView alloc] initWithImage:Balloon];
// Sizes the image to the correct size
BalloonView.frame = CGRectMake(0, 0, 50, 100);
// Centers the image using the x and y coordinates
BalloonView.center = CGPointMake(x,y);
// Adds the image view to the view
[self.view addSubview:BalloonView];
// Adds the image view to the array
[BalloonArray addObject:BalloonView];
}
-(void)PopBalloons:(id)sender
{
// Removes each image in the array out of the main view
for(UIImageView *Test in BalloonArray)
{
[Test removeFromSuperview];
}
// Removes all object from the array
[BalloonArray removeAllObjects];
}
@end
你确定你没有陷入无限循环吗?什么行为导致代码“冻结”?你可以发布调用add balloon方法的代码吗?备注:变量和方法名称应以小写字母开头。另外,如果“发件人”是UIButton,则将其作为UIButton而不是id传递。 id可以是任何对象,这显然是不安全的。另一个,请不要使用iVars,使用属性。您可以查看文档中的属性(气球阵列和气球名称应该是属性)。 –
帮你一个忙,并尝试遵守通常的编码约定:方法和变量名通常以小写字母开头。这就是说,它冻结在哪里?你是否与调试器断了,看看它在哪里?你创建并添加了多少个子视图? – DarkDust
我检查了无限循环并“关闭”了所有可检查的循环。我不相信这是无限循环问题,并用换行符检查每一个循环。我对目标c的知识非常有限,但我认为这可能是内存分配问题。 – user3780458