我对Obj-c委托做错了什么

时间:2013-02-08 11:35:03

标签: ios objective-c

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

2 个答案:

答案 0 :(得分:2)

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

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

当您在两个视图控制器之间进行转换时,您必须通过代理,例如- prepareForSegue:[self.navigationController pushViewController:vc animated:YES]

答案 1 :(得分:0)

Here is Best site with source code for learn basic about protocol.

////// .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 file

@synthesize mypDelegate;
.
.
.
.
- (void)processComplete
{
    [[self mypDelegate] myProtocolMethodOne];
}