我的第一篇文章發佈到論壇,但我一直在使用過去幾個月發佈的答案,並找到非常有用的答案!我仍然在學習目標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