Tableview显示警报错误

时间:2015-01-10 22:59:04

标签: ios objective-c uialertview

我正在编写一个简单的tableview应用程序,当点击该行时,会显示警报。

(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *rowValue =self.greekLetters[indexPath.row];
   // NSString *message=[[NSString alloc] initWithFormat:@"You selected%@!",rowValue];

   if (indexPath.row==0) {
        NSString *message=[[NSString alloc] initWithFormat:@"This is course aaaaa",rowValue];
    }

    if (indexPath.row==1) {
        NSString *message=[[NSString alloc] initWithFormat:@"This is course aaaaa"];
    }


    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Course introduction" message:message delegate:nil cancelButtonTitle:@"Return to courses list" otherButtonTitles:nil, nil];

    [alert show];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

但是,Xcode不喜欢我的if语句,而以下语句可以使用。

NSString *message=[[NSString alloc] initWithFormat:@"You selected%@!",rowValue];

有人能给我一个如何在这里使用这个消息的例子吗?

2 个答案:

答案 0 :(得分:1)

这是范围问题。您需要在if语句之前声明消息:

NSString *message;

if (indexPath.row==0) {
    message=[[NSString alloc] initWithFormat:@"This is course aaaaa",rowValue];
}

else if (indexPath.row==1) {
    message=[[NSString alloc] initWithFormat:@"This is course aaaaa"];
}

UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Course introduction" message:message delegate:nil cancelButtonTitle:@"Return to courses list" otherButtonTitles:nil];

[alert show];
[tableView deselectRowAtIndexPath:indexPath animated:YES];

但是,如果课程编号由行号确定:

NSString *rowValue =self.greekLetters[indexPath.row];

NSString *message = [[NSString alloc] initWithFormat:@"This is course %@",rowValue];

UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Course introduction" message:message delegate:nil cancelButtonTitle:@"Return to courses list" otherButtonTitles:nil];

[alert show];
[tableView deselectRowAtIndexPath:indexPath animated:YES];

答案 1 :(得分:0)

您已忘记在第一个if语句中加入%@

NSString *message= [[NSString alloc] initWithFormat:@"This is course aaaaa %@",rowValue];

顺便说一下,根本不需要[[NSString alloc] init],只需使用[NSString stringWithFormat:...]

相关问题