2012-04-23 96 views
0

我在didSelectRowAtIndexPath方法委託方法如下代碼:問題與指針

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

    Exercise *exerciseView = [[Exercise alloc] initWithNibName:@"Exercise" bundle:nil]; //Makes new exercise object. 

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 
    NSString *str = cell.textLabel.text; // Retrieves the string of the selected cell. 

    exerciseView.exerciseName.text = str; 

    NSLog(@"%@",exerciseView.exerciseName.text); 

    [self presentModalViewController:exerciseView animated:YES]; 
} 

在此,筆者嘗試採取選定單元格的文本,以及IBOutlet中的UILabel exerciseName設置該字符串。

我的方法編譯,但是當我運行NSLog,它將它設置爲str後打印UILabel的textvalue,它將返回null。我覺得這是一個指針問題,但似乎無法理解它。任何人都可以澄清事情嗎?

+0

當你NSLog str你沒有得到空?你在使用ARC嗎? – shein 2012-04-23 02:58:53

+0

請在你的其他類似問題中看到我的評論。 – danh 2012-04-23 03:00:53

回答

1

問題是半初始化視圖控制器。在初始化子視圖的內容之前,需要讓它生成。

Exercise.h

@property(strong, nonatomic) NSString *theExerciseName; // assuming ARC 

- (id)initWithExerciseName:(NSString *)theExerciseName; 

Exercise.m

@synthesize theExerciseName=_theExerciseName; 

- (id)initWithExerciseName:(NSString *)theExerciseName { 

    self = [self initWithNibName:@"Exercise" bundle:nil]; 
    if (self) { 
     self.theExerciseName = theExerciseName; 
    } 
    return self; 
} 

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    exerciseName.text = self.theExerciseName; 
} 

調用新的初始化從didSelect方法。

Exercise *exerciseView = [[Exercise alloc] initWithExerciseName:str]; 

但請使用cellForRowAtIndexPath中的邏輯來獲取該str,而不是通過調用它。

+0

這很有道理。謝謝! – TopChef 2012-04-23 03:22:17

+0

我可以問一下這一行的含義嗎? @synthesize theExerciseName = _theExerciseName; – TopChef 2012-04-23 03:23:07

+0

當然 - 爲屬性創建getter和setter,並給它一個別名,使它不會與堆棧變量和參數相沖突(請參閱init參數如何具有相同的名稱,但沒有編譯器警告)。 – danh 2012-04-23 03:27:40