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 练习名称设置为该字符串。

我的方法可以编译,但是当我运行 NSLog(在将 UILabel 设置为 str 后打印 UILabel 的文本值)时,它返回 null。我觉得这是一个指针问题,但似乎无法掌握它。任何人都可以澄清事情吗?

4

1 回答 1

1

问题是半初始化的视图控制器。在初始化子视图的内容之前需要让它构建。

练习.h

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

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

练习.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。

于 2012-04-23T03:14:51.420 回答