详细视图控制器未将值传递回主控制器

时间:2013-11-06 21:00:52

标签: ios segue viewcontroller

我有以下语句从json feed填充表。从表中选择一行后,它会传回原始控制器,以便再次查询api以填充某些字段。

问题是传回的值与已选择的单元格无关。

这是我的代码。

在详细视图控制器中

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    NSDictionary *addressdict = [jsonData objectAtIndex:indexPath.row];
    NSString *address = [addressdict objectForKey:@"StreetAddress"];
    idnumber = [addressdict objectForKey:@"Id"];
    cell.textLabel.text = address;
    cell.detailTextLabel.text = idnumber;
    return cell;
}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Make sure your segue name in storyboard is the same as this line
    if ([[segue identifier] isEqualToString:@"sendAddress"])
    {
        // Get reference to the destination view controller
        SignUpViewController *controller = (SignUpViewController *)segue.destinationViewController;
        // Pass any objects to the view controller here, like...
        controller->idnumber = idnumber;
    }
}

在我的主视图控制器中,我这样做

NSLog(@"The Address ID is: %@",idnumber);

但值是返回不正确。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

您可以使用委托将数据传回上一个UIViewController。

E.g。

<强> UIViewControllerB.h

// Declare a protocol that conforms to NSObject
@protocol UIViewControllerBDelegate <NSObject>

// @required is the default, but means that the delegate must implement the following methods
@required
- (void)viewController:(UIViewController)aViewController didSelectIDNumber:(NSNumber *)anIDNumber;

@end

<强> UIViewControllerB.m

@interface UIViewControllerB : NSObject

// Keep a reference to the delegate so we can call the above methods
@property (weak, nonatomic) id<UIViewControllerBDelegate> delegate;

@end


@implementation UIViewControllerB

 - (NSNumber *)idNumberAtIndex:(int)anIndex
 {
    NSNumber *idNumber = nil;

    if (jsonData && anIndex <= [jsonData count])
    {
        NSDictionary *addressDictionary = jsonData[anIndex];

        idNumber = addressDictionary[@"Id"];
    }
    return idNumber;
 }

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     // When a row is selected let the delegate know the idNumber
     [self.delegate viewController:self didSelectIDNumber:[self idNumberAtIndex:indexPath.row]];
}

@end

<强> UIViewControllerA.m

// Make UIViewControllerA conform the the UIViewControllerBDelegate
@implementation UIViewControllerA <UIViewControllerBDelegate>

// Implement the required UIViewControllerB Delegate Method
- (void)viewController:(UIViewController *)aViewController didSelectIDNumber:(NSNumber *)anIDNumber
{
    // do something with the id number
}

答案 1 :(得分:0)

这是绝对错误的,您尝试在函数idnumber中设置cellForRowAtIndexPath的值,在您的情况下,它将具有tableview显示的最后一个值。

您应该尝试在tableview方法idnumber中获取didSelectRowAtIndexPath