2011-11-08 14 views
1

我是新來的客觀C編程,我處於一個需要真正快速創建iPhone應用程序的位置。 我正在使用XCode 4.2objective C從視圖切換到另一個

我有一個問題,從一個視圖轉移到另一個視圖的NSString變量。 這兩種觀點都在兩套不同的.h和.M類

在.hi一流

都在的firstView的.M像這樣

@interface firstview : UIViewController { 
NSString *test; 
} 

-(IBAction)testbutton 
@end 

我有

-(IBAction)testbutton{ 
secondView *second; 
[second setText:text]; //set text is a function that will take an NSString parameter 
second= [[secondView alloc] initWithNibName:nil bundle:nil]; 
[self presentModalViewController:second animated:YES]; 
} 
在secondView的.H

我寫

@interface secondView : UIViewController{ 
-IB 
} 
+0

你的問題是什麼? –

回答

1

你有正確的的想法,但你想在second之前撥打-setText:指向一個有效的對象!做到這一點,而不是:

-(IBAction)testbutton{ 
    secondView *second; 
    second = [[secondView alloc] initWithNibName:nil bundle:nil]; 
    [second setText:text]; //set text is a function that will take an NSString parameter 
    [self presentModalViewController:second animated:YES]; 
} 

而且,你給你的secondView類的界面看起來不正確的和不完整的 - 我不知道你想與-IB部分做什麼。如果按照通常的Objective-C命名約定,並且使用大寫字符開始類名稱,它將在未來提供幫助:SecondView而不是secondView。最後,我建議不要命名以「... View」結尾的視圖控制器,因爲這很容易將視圖控制器與UIView混淆。總之,它應該是這個樣子:

@interface SecondViewController : UIViewController{ 
    NSString *text; 
} 
@property (retain, nonatomic) NSString *text; 
@end 

聲明text爲一個實例變量是可選的有 - 如果你不這樣做,如果你合成存取您text編譯器將創建伊娃屬性。調用它setText:

-(IBAction)testbutton{ 
    secondView *second; 
    second = [[secondView alloc] initWithNibName:nil bundle:nil]; 
    [second setText:text]; //set text is a function that will take an NSString parameter 
    [self presentModalViewController:second animated:YES]; 
} 

在原來的版本中,你初始化(即實例化)你的第二個觀點

+0

+1擊敗了16秒。 – MusiGenesis

0

你的代碼改成這樣。你需要初始化它,然後然後設置文本。

0

您需要在分配和初始化後設置文本。

-(IBAction) testButton { 
    secondView *second = [[[secondView alloc] initWithNibName:nil bundle:nil] autorelease]; 
    [second setText:text]; 
    [self presentModalViewController:second animated:YES]; 
} 
相關問題