ViewBでデリゲートを定義し、それをViewAに実装するとします。適切なタイミングで(たとえば、戻るボタンがタップされたとき)、ViewBはデリゲートメソッドを呼び出し、値をパラメーターとして渡します。
このようなもの:
ViewB.h
// Define a delegate protocol allowing
@protocol ViewBDelegate
// Method of delegate called when user taps the 'back' button
-(void) backButtonSelected:(id) object;
@end
@interface ViewB : UIViewController
// property to hold a reference to the delegate
@property (weak)id<ViewBDelegate> delegate;
-(IBAction)backButtonSelected:(id)sender;
@end
ViewB.m:
@implementation ViewB
...
-(IBAction)backButtonSelected:(id)sender{
NSObject *someObjectOrValue = nil;
// Invoke the delegates backButtonSelected method,
// passing the value/object of interest
[self.delegate backButtonSelected:someObjectOrValue];
}
@end
ViewA.h:
#import "ViewB.h"
// The identifier in pointy brackets (e.g., <>) defines the protocol(s)
// ViewA implements
@interface ViewA : UIViewController <ViewBDelegate>
...
-(IBAction)someButtonSelected:(id)sender;
@end
ViewA.m:
-(IBAction)someButtonSelected:id @implementation ViewA
...
// Called when user taps some button on ViewA (assumes it is "hooked up"
// in the storyboard or IB
-(IBAction)someButtonSelected:(id)sender{
// Create/get reference to ViewB. May be an alloc/init, getting from storyboard, etc.
ViewB *viewB = // ViewB initialization code
// Set `ViewB`'s delegate property to this instance of `ViewA`
viewB.delegate = self;
...
}
// The delegate method (defined in ViewB.h) this class implements
-(void)backButtonSelected:(id)object{
// Use the object pass as appropriate
}
@end