Search code examples
iosios7

How do you save the user selected string in the UITableView


I'm looking to have the string selected (indicated by the accessory check mark) to be saved into a string to be used and displayed in a different view controller. As an example, I have these different objects in my array "Business", "Computer Science", etc. In the next view controller I want my empty label to display the string the user has selected.

My code:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.array = [[NSArray alloc]initWithObjects:@"Business",@"Computer Science", @"Economics", @"Mathematics",nil];

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
}

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryNone;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma Table View Methods

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.array count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }

    cell.textLabel.text = [self.array objectAtIndex:indexPath.row];

    return cell;
}

@end

Solution

  • you can try this way

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
    
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        NSLog(@"%@",cell.textLabel.text);
    
    }