2010-05-21 210 views
0

我想在touchesBegan方法中創建一個名爲theImageView的UIImageView,然後我可以移動到touchesMoved中的新位置。目前,我在touchesMoved中收到「未聲明」的錯誤,其中我設置了theImageView的新位置。在內存中保留對象(iPhone SDK)

我該怎麼做才能保持theImageView這兩種方法之間的內存?

編輯:我無法申報theImageView在@interface,因爲我需要創建一個圖像的每一個特定點被觸摸的時間。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    ... 
    UIImageView *theImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.png"]]; 
    theImageView.frame = CGRectMake(263, 228, 193, 300); 
    [theImageView retain]; 
    ... 
} 

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { 
    ... 
    theImageView.frame = CGRectMake(300, 300, 193, 300); 
    ... 
} 

回答

6

你宣佈一個方法/函數變量,這使得它的局部變量(即只存在內部的功能的變量)。要使其在其他方法中可用,必須在類的@interface中將其聲明爲實例變量。

+0

謝謝你的回答。我很抱歉,但我的意思是說,我無法這樣做,因爲我試圖創建一個新的UIImageView對象每次觸摸屏幕的預定區域。這意味着我需要動態創建這些對象,因此我無法在@interface中聲明它們。有沒有其他的方式來解決這個問題?再次感謝你的幫助。 – Chris 2010-05-21 05:38:07

+0

@Chris:我不明白爲什麼你認爲你無法做到這一點。您可以重新分配實例變量以指向新的對象。 – Chuck 2010-05-21 05:49:36

+0

或者有一個實例變量來存放放置UIImageViews的NSMutableArray。 – 2010-05-21 06:38:35