[英]What I am doing wrong with Obj-c delegate
我在firstViewController中在Xcode中创建了一个新的选项卡式视图项目,我创建了这样的协议
@protocol myProtocol <NSObject>
-(void)myProtocolMethodOne;
@end
@interface FirstViewController : UIViewController
@property (weak) id<myProtocol> mypDelegate;
- (IBAction)button1Tap:(id)sender;
@end
在.m文件中我做到了这一点
@synthesize mypDelegate;
.
.
.
- (IBAction)button1Tap:(id)sender
{
[mypDelegate myProtocolMethodOne];
}
这是secondViewController .h文件
@interface SecondViewController : UIViewController <myProtocol>
@property (strong) FirstViewController *fvc;
@end
这是.m文件
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(@"Second", @"Second");
self.tabBarItem.image = [UIImage imageNamed:@"second"];
_fvc = [[FirstViewController alloc]init];
[_fvc setMypDelegate:self];
}
return self;
}
-(void)myProtocolMethodOne
{
NSLog(@"2nd VC");
[[self tabBarItem]setBadgeValue:@"ok"];
}
myProtocolMethodOne无法正常工作,我做错了什么?
_fvc = [[FirstViewController alloc]init];
[_fvc setMypDelegate:self];
您将委托设置为全新的FirstViewController
,但不是触发您的方法的那个- (IBAction)button1Tap:(id)sender
当你在两个视图控制器之间进行转换时,你必须传递你的委托,例如在- prepareForSegue:
或者当你做[self.navigationController pushViewController:vc animated:YES]
////// .h文件
#import <Foundation/Foundation.h>
@protocol myProtocol <NSObject>
@required
-(void)myProtocolMethodOne;
@end
@interface FirstViewController : UIViewController
{
id <myProtocol> mypDelegate;
}
@property (retain) id mypDelegate;
- (IBAction)button1Tap:(id)sender;
@end
///////// .m文件
@synthesize mypDelegate;
.
.
.
.
- (void)processComplete
{
[[self mypDelegate] myProtocolMethodOne];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.