我想分配SecondViewController作爲FirstViewController的代理對象(如果我理解正確)。但是,FirstViewController不會向SecondViewController發送任何消息。Xcode:委託對象是否向委託對象發送消息?
我是否允許假裝SecondViewController確實從FirstViewController獲得消息並響應FirstViewController? (注:我SecondViewController負責,有一個按鈕的視圖當我按我的SecondViewController的視圖中的按鈕,我希望它告訴FirstViewController更新其視圖)
FirstViewController.h
#import <UIKit/UIKit.h>
@protocol FirstViewControllerDelegate <NSObject>
@optional
- (void) setAnotherLabel;
@end
@interface FirstViewController : UIViewController {
IBOutlet UILabel *label;
id <FirstViewControllerDelegate> delegate;
}
@property (nonatomic, retain) IBOutlet UILabel *label;
@property (nonatomic, assign) id <FirstViewControllerDelegate> delegate;
- (void) pretendLabel;
- (void) realLabel;
@end
FirstViewController.m
#import "FirstViewController.h"
@implementation FirstViewController
@synthesize label;
@synthesize delegate;
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void) setAnotherLabel;
{
label.text [email protected]"Real";
[self.view setNeedsDisplay];
}
- (void) pretendLabel;
{
label.text [email protected]"Pretend";
[self.view setNeedsDisplay];
}
- (void) realLabel;
{
[self setAnotherLabel];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[email protected]"Load";
[self pretendLabel];
}
...
@end
SecondViewController.h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "FirstViewController.h"
@interface SecondViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate, FirstViewControllerDelegate>
{
UIImage *image;
IBOutlet UIImageView *imageView;
}
- (IBAction) sendPressed:(UIButton *)sender;
- (IBAction) cancelPressed:(UIButton *)sender;
@end
SecondViewController.m
#import "SecondViewController.h"
@implementation SecondViewController
- (IBAction) sendPressed:(UIButton *)sender
{
FirstViewController *fvc = [[FirstViewController alloc] init];
[fvc setDelegate:self];
//how do I find out if I'm actually the delegate for FirstViewController at this point?
[fvc realLabel];
self.tabBarController.selectedIndex = 0;//switch over to the first view to see if it worked
}
感謝您的解釋IWN :-)在過去的幾天裏,我的邏輯錯誤(即這個問題)一直困擾着我。我感到輕鬆多了。再次感謝。 – NateHill
很高興幫助! – InsertWittyName