2012-06-06 37 views
0

我是新來的Objective-C,我試圖編寫一個iPhone應用程序。爲什麼我的Objective-C代碼拋出異常?

這是我的代碼:

頭文件:

#import <UIKit/UIKit.h> 

@interface TutorialViewController : UIViewController{ 
    UILabel *labelText; 
    UIImageView *imageView; 
} 
@property(nonatomic,retain) IBOutlet UILabel *labelText; 
@property(nonatomic,retain) IBOutlet UIImageView *imageView; 

-(IBAction) click:(id) sender; 

@end 

,這是實現:

#import "TutorialViewController.h" 

@implementation TutorialViewController 
@synthesize labelText; 
@synthesize imageView; 

-(void) click:(id)sender { 
    imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"1.png"]]; 
    NSString *titleOfButton = [sender titleForState:UIControlStateNormal]; 
    NSString *newText = [[NSString alloc]initWithFormat:@"%@",titleOfButton]; 
    // Change Image When Clicking Color Button 
    if([titleOfButton isEqualToString:@"Blue"]){ 
     NSLog(@"Blue"); 
     UIImage *image = [UIImage imageNamed:@"1.png"]; 
     imageView.image = image; 
     [image release]; 
    }else{ 
     UIImage *image = [UIImage imageNamed:@"2.png"]; 
     imageView.image = image; 
     [image release]; 
     NSLog(@"Else"); 
    } 
    labelText.text = newText; 
    [newText release]; 
} 
- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
} 
#pragma mark - View lifecycle 
- (void)viewDidUnload 
{ 
    [super viewDidUnload]; 
    self.labelText = nil; 
} 
-(void) dealloc{ 
    [labelText release]; 
    [imageView release]; 
    [super dealloc]; 
} 
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    return (interfaceOrientation == UIInterfaceOrientationPortrait); 
} 

@end 

當我啓動應用程序,它拋出一個異常:

'NSInternalInconsistencyException', reason: '-[UIViewController _loadViewFromNibNamed:bundle:] loaded the "TutorialViewController" nib but the view outlet was not set.' 

Can any on e幫我用我的代碼?

此外,您能否告訴我關於我的代碼中的不良書面行爲。

很多很多謝謝!

+0

從你分配內存到TutorialViewController和加載的地方,你可以添加代碼嗎? – rishi

+0

與您的問題無關,但您的內存管理問題存在。你釋放你沒有分配,複製或保留的東西。 – Chuck

回答

3

將Xib中的根UIView連接到文件所有者的視圖。

enter image description here

+0

謝謝Jacky Boy,它確實有效。但在此之前,我已經將UIImageView連接到FileOwner,但它不起作用。他們之間有什麼關係? – MrROY

+0

您將「UIImageView」連接到文件所有者,但是連接到了哪裏?對於您創建的IBOutlet?到根視圖? – Peres

+0

給我創建的IBOutlet。 – MrROY

0

好了,錯誤信息似乎很清楚:

加載「TutorialViewController」筆尖但認爲出口是不是 集」

檢查TutorialViewController筆尖上的插座。看起來像查看插座沒有連接任何東西。要修復它,請將頂層視圖連接到插座(控制拖動)。

1

打開你的.xib文件,然後在對象點擊查看,然後在引用奧特萊斯點擊連接督察,並從那裏控制+點擊圓圈並將其拖動到文件的所有者,並從彈出菜單中選擇視圖.... :)

Connecting Outlets

EDIT: 

您的看法是主要的UIView,無論你會把它或在它的層次結構會自動顯示。正如你在其中使用了UIImageView(你可以在對象中看到視圖和對象的層次結構,在PlaceHolders下可以看到xib到左邊的列)。將UIView(父視圖)連接到文件所有者時。它顯示了包含在主視圖中的所有其他視圖。因此,當您將主視圖連接到文件所有者時,它解決了您的問題。

+0

我已經這樣做了,但它不起作用。 – MrROY

+0

它連接正確嗎? –

+0

嗯,我連接imageView(看我的代碼)FileOwner ...不是根視圖。 – MrROY

相關問題