将协议/委派存储在正确的对象中

时间:2013-12-09 05:18:50

标签: objective-c ios7

我创建了一个User类,其中第一个视图控制器中分配了User对象。在第一个视图控制器中,一些对象属性填充了一些数据。我正在使用第二个视图控制器来获取其他用户信息,然后将其发送回第一个视图控制器以存储在剩余的对象属性中。我正在使用协议和委托来完成这项工作。我按照这里的说明操作: Passing Data between View Controllers

看起来我做的一切都正确,除了我不知道如何将结果与我的对象的属性相关联。能够在第一个调用第二个视图控制器的视图控制器中返回原始方法会很高兴。这可能吗?我所看到的很多答案都需要全局变量,但我不确定这对我的案例是否必要。

/**Implementation of Main View Controller **/
-(IBAction)signUpButton
{

    User * firstUser = [[User alloc] init];

    firstUser.userName = userNameField.text;
    firstUser.password = passwordField.text;

    /**second view controller **/

    SetUp *setUpView = [[SetUp alloc] initWithNibName:Nil bundle:Nil];

    setUpView.delegate = self;

    [self presentViewController:setUpView animated:YES completion:^{ }];

    firstUser.zone = holdZoneInfo;
    firstUser.area= holdAreaInfo;

    NSLog(@"first User %@, %@, %@, %@",firstUser.userName, firstUser.password, firstUser.zone, firstUser.area);

    /**username and password display fine, but zone and area are null since the delegation operation hasn't been completed as this point **/

}

/**Protocol Method Declared in Main View Controller**/
-(void) sendUserInfoBack: (SetUp *) SetUpController didFinishWithZone:(NSString*)item1 didFinishWithArea:(NSString*) item2
{

    holdZoneInfo = item1;
    holdAreaInfo = item2;

    NSLog(@"Delegation result: %@ %@", holdZoneInfo, holdAreaInfo);
    /**This displays correctly**/

}

/**Second view controller implementation file**/

-(IBAction)goToMainView:(id)sender
{
    NSString * neededZoneStore = zoneField.text;
    NSString * neededAreaStore = areaField.text;

    User * user = [[User alloc] init];

    user.zone = neededZoneStore;
    user.area = neededAreaStore;

    [self.delegate sendUserInfoBack:self didFinishWithZone: neededZoneStore didFinishWithArea: neededAreaStore];


    [self dismissViewControllerAnimated:YES completion:NULL];
}

所以我需要firstUser.zone = holdZoneInfo,但我无法实现这一目标

1 个答案:

答案 0 :(得分:0)

SetUp视图控制器类中,声明user类型的User属性。当您alloc / init SetUp视图控制器将user属性设置为firstUser时。当SetUp视图控制器调用委托方法时,返回firstUser对象。

SetUp视图控制器用来自用户的数据填充User对象。

// in signUpButton
setUpView.user = firstUser;

重构委托方法的名称:

- (void)setUpViewController:(SetUp *)controller exitedWithUser:(User *)user;