2010-01-11 56 views
1

我創建了一個UIView併爲其添加了標籤,後者將其分配給Controller。 現在,每當我點擊我查看它爲我「EXC_BAD_ACCESS」。通過代碼創建UIView並在iphone中添加事件

下面是我的代碼。

//create a UIView in App Delegate 
UIView *viewPtr = [[[UIView alloc] initWithFrame:frmRect] autorelease]; 

//created a Button and added to UIView 
UIButton *btnPointer = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
btnPointer.frame = cgframe; // provides both a position and a size 
[btnPointer setTitle:btnLabelText forState:UIControlStateNormal]; 
[btnPointer addTarget:self action:@selector(generate:) forControlEvents:UIControlEventTouchUpInside]; 
[viewPtr addSubview:btnPointer]; 

//Now need to add this UIView to a controller 
viewController.view = viewPtr; 

我能夠在表單上顯示的按鈕,但是當我點擊窗體或上按鈕我得到 「EXC_BAD_ACCESS」。

回答

1

你應該建立在你這樣的視圖控制器的.m文件的視圖。

- (void)loadView 
    { 
     UIView *viewPtr = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]]; 

    //created a Button and added to UIView 
    UIButton *btnPointer = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    btnPointer.frame = cgframe; // provides both a position and a size 
    [btnPointer setTitle:btnLabelText forState:UIControlStateNormal]; 
    [btnPointer addTarget:self action:@selector(generate:) forControlEvents:UIControlEventTouchUpInside]; 
    [viewPtr addSubview:btnPointer]; 

    //Now need to add this UIView to a controller 
    self.view = viewPtr; 
[viewPtr release]; 
    } 

希望這會有所幫助。

感謝,

Madhup

0

什麼是self[btnPointer addTarget:self ...?叫generate:?你嘗試過在那裏調試嗎?

1

改用自動釋放

UIView *viewPtr = [[[UIView alloc] initWithFrame:frmRect] autorelease];

對.h文件創建的UIView * viewPtr,只有做好了釋放dealloc方法

所以,你會對你的聲明。 .h文件


UIView *viewPtr; 

你.m文件將與以下行,當你實例化viewPtr在同一個地方,你以前做什麼,但沒有自動釋放,並在dealloc方法釋放如下:


viewPtr = [[UIView alloc] initWithFrame:frmRect]; 
. 
. 
. 
. 
. 
. 
. 
. 

- (void)dealloc { 
    [viewPtr release]; 
    [super dealloc]; 
}

自動釋放是在你的代碼的主要問題,因爲當你這樣做,你的UIView不會對任何事件做出反應。

乾杯,
VFN

+0

viewController.view = viewPtr; - 這一行保留viewPtr,所以不要認爲自動釋放導致這裏的問題 – Vladimir 2010-01-11 13:15:50

+0

儘量不要做autorelease。你會看到問題出在那裏。 – vfn 2010-01-11 13:26:21

+0

只能進行測試,嘗試刪除autorelease,並讓視圖沒有釋放調用,僅用於測試。如果它有效,你可以按照我的建議回答 – vfn 2010-01-11 13:27:37

0

由於VFN說,因爲你釋放視圖太早這個你的錯誤。我會問的問題是爲什麼這種情況有所不同?

通常在這樣的分配:

viewController.view = viewPtr; 

viewPtr被保留,你將是正確的自我釋放。但look at the definition

@property(nonatomic, retain) UIView *view 

這意味着任何值僅僅是分配和不自動保持。