具有自定义类对象的IOS委派;将对象从模态视图传递到父视图

时间:2014-03-01 22:55:48

标签: ios protocols delegation

首先,我为提出另一个代表团问题而道歉。我读了很多,找不到任何复杂的东西......

这就是我在做什么...... 在我的应用程序中,我有一个ViewController:CollisionViewController,我想让用户选择两个涉及碰撞的车辆。所有车辆都使用CoreData存储,并在SelectVehicleViewController中以模态方式显示。 SelectVehicleViewController使用UICollectionView列出所有车辆。在CollisionViewController中,我有Vehicle1和Vehicle2的属性,它们是描述车辆属性的自定义类。

在CollisionViewController中,我使用UIButton让用户首先选择Vehicle1,然后以模态方式呈现SelectVehicleViewController中的Vehicle2。

我在使用模态SelectVehicleViewController之前使用seques来确定按下了哪个按钮。

如何设置一个协议,允许用户将选定的车辆从模态视图传递到CollisionViewController中的正确车辆对象?

1 个答案:

答案 0 :(得分:0)

collisionViewController应符合您的协议。

collisionViewController.h

#import "SelectVehicleViewController.h"
@interface ContactViewController : UIViewController <SelectVehicleDelegate>

collisionViewController.m

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqual:@"segueName"]) {
        SelectVehicleViewController* VC = segue.destinationViewController;
        VC.delegate = self;
        //here you should probably send if you will select the vehicule 1 or 2
    }
}

- (void)ViewController:(UIViewController *)sender
         didUpdateData:(NSString *)value {
    //do what you need with new data
    //here you should have info if it is for vehicle 1 or 2
}

SelectVehicleViewController.h

@protocol SelectVehicleDelegate;

@interface SelectVehicleViewController : UIViewController

@property (nonatomic, assign) id <SelectVehicleDelegate> delegate;

@end

@protocol SelectVehicleDelegate <NSObject>

- (void)ViewController:(UIViewController *)sender
             didUpdateData:(NSString *)value;      //adapte according to what you should send back

@end

SelectVehicleViewController.m

//somewhere in a button click or....
[self.delegate ViewController:self didUpdateData:@"new value"];
  //in this function you should have info if it is for vehicle 1 or 2