Xcode:委托对象是否必须向委托对象发送消息?
|
我正在尝试将SecondViewController分配为FirstViewController的委托对象(如果我理解正确的话)。但是,FirstViewController不会向SecondViewController发送任何消息。
我是否可以假装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 =@\"Real\";
[self.view setNeedsDisplay];
}
- (void) pretendLabel;
{
label.text =@\"Pretend\";
[self.view setNeedsDisplay];
}
- (void) realLabel;
{
[self setAnotherLabel];
}
- (void)viewDidLoad
{
[super viewDidLoad];
label.text=@\"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
}
没有找到相关结果
已邀请:
1 个回复
导力疵谜
方法中,您正在创建FirstViewController的新实例-这与标签栏控制器中的FirstViewController不同,为什么调用and5ѭ无效。 第二点是您似乎误解了委托的工作原理-在发布的代码中没有理由要委托。 阅读有关与代表打交道的好书:http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CocoaFundamentals/CommunicatingWithObjects/CommunicateWithObjects.html 至于您的问题的解决方案,有几种选择: 从SecondViewController发布一个FirstViewController正在观察的通知(网络上有关通知的大量信息)。 在self.tabBarController.viewControllers数组中获取FirstViewController的特定实例,然后从那里调用该方法。就像是...
除此之外,还有更多可用的选项,但是以上内容将为您提供一个开始研究满足您需求的最佳方法的良好开端。 希望这可以帮助。