0

我在 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 不工作,我做错了什么?

4

2 回答 2

2
_fvc = [[FirstViewController alloc]init];
[_fvc setMypDelegate:self];

您正在将委托设置为全新的FirstViewController,但不是触发您的方法的委托- (IBAction)button1Tap:(id)sender

当你在你的 2 个视图控制器之间进行转换时,你必须传递你的委托,例如在你做的- prepareForSegue:时候或当你做的时候[self.navigationController pushViewController:vc animated:YES]

于 2013-02-08T11:40:43.927 回答
0

这是学习协议基础知识的最佳源代码站点。

////// .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];
}
于 2013-02-08T11:44:31.033 回答