我在论坛上的第一篇文章,但我一直在使用过去几个月发布的答案,并找到非常有用的答案!我还在学习目标c并且还在学习一些基础知识。
我的代码是几百行,所以我不想发布整个代码。代码的基本前提是将一系列随机图像加载到屏幕上的随机位置。
当我试图找出如何处理这个想法时,我做了一个简单的测试版本,当按下按钮时会添加一个气球,然后当你点击pop气球时删除所有创建的气球图像。
这个气球代码运行得很好,然后我将这个相同的概念添加到我的主代码中。但是现在当我只使用更大规模的代码时,代码将冻结在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
答案 0 :(得分:0)
使方法-(void)AddBalloon:(id)sender
在单独的线程上运行。也许你可以使用[NSThread detachNewThreadSelector:@selector(myThreadMainMethod:) toTarget:self withObject:nil];
。看看Apple Documentation