2012-04-23 102 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