2010-10-11 37 views
0

我有一個TapDetectingImageView類在使用後屬於內存,因爲我沒有在我的代碼中重用它。 我現在更改我的代碼以重新使用它,而不是每次都重新創建一個新代碼。試圖重用變量以避免被遺棄的內存

目標是配置TapDetectingImageView對象並將其放入視圖中。我會做8次,但下面的代碼,只有最後一個顯示。我確定我錯過了什麼,但是什麼? ;)

持有imageViews的視圖是potatoeView。我正在添加新的TapDetectingImageView:

[potatoeView addSubview:imageView]; 

該代碼有什麼問題?

for (int i = 0; i <= numberOfPotatoes-1; i++) 
    { 
     NSLog(@"potatoesView Generation : %d",i); 

     NSArray *imgArray = [[NSArray alloc] initWithArray:[p objectAtIndex:i]]; 
     UIImage *img1 = (UIImage *) [imgArray objectAtIndex:0]; 
     UIImage *img2 = (UIImage *) [imgArray objectAtIndex:1]; 
     NSString *imgName = (NSString *) [imgArray objectAtIndex:2]; 

     if (imageView == nil) { 
      imageView = [[TapDetectingImageView alloc] initWithImage:img1 imageHighlighted:img2]; 
     }else { 

      [imageView setImage:(UIImage *)img1]; 
      [imageView setImageHighlighted:(UIImage *)img2]; 

     } 

     [imageView setDelegate:self]; 

     // setup each frame to a default height and width, it will be properly placed when we call "updateScrollList" 

     CGRect rect = imageView.frame; 

     rect.size.height = [potatoesSize floatValue] ; 
     rect.size.width = [potatoesSize floatValue] ; 

     imageView.frame = rect; 

     [imageView setName:(NSString *)imgName]; 


     imageView.tag = i+1; // tag our images for later use when we place them in serial fashion 

     NSValue *val = [potatoesSizeAndPositions objectAtIndex:i]; 
     CGPoint point = [val CGPointValue]; 
     imageView.center = point; 

     [potatoeView addSubview:imageView]; 

     [imgArray release]; 
    } 

回答

1

您只創建一個視圖,將其設置爲子視圖,然後將其更改爲n-1次。刪除if (imageView==nil)並創建全部8個。

+0

嗨,那是我之前做過的,但是當解散視圖時,這8個視圖仍然在記憶中。我沒有泄漏也沒有殭屍,但似乎有一些遺棄的內存在設備上測試時會產生內存不足的崩潰......我正在尋找如何解決這個問題......我將回到先前的代碼創建8個視圖並釋放事後...感謝你的答案。 – Tibi 2010-10-11 09:19:09

+0

如果你的內存崩潰很少,那不是因爲有八個UIViews。使用各種分析工具來查找問題,而不是在應用程序中進行瘋狂的刺探。 – zem 2010-10-11 20:16:54

+0

ok ooook ;-)我回來了並且通過儀器分析,看起來我已經發布了一些東西......必須重新分析我的代碼......對不起;-) – Tibi 2010-10-12 07:03:14

3

您似乎從根本上誤解了您的觀點是如何繪製的。當你使用八個不同的位置和圖像設置同一個視圖實例時,它不會將它們全部「印記」在畫布上。在主運行循環開始繪製視圖之前,它的狀態將不會被查詢,此時它會詢問您的視圖的框架和內容等等來繪製它。如果你想用UIViews繪製八個不同的圖像,你需要八個不同的視圖。