iOS:我不确定,但我的代表并没有像我计划的那样锻炼

时间:2013-12-13 14:51:34

标签: ios objective-c delegates protocols

我有这个代表没有按计划工作,我有这样设置。我想调用函数NSLog(show);我不太确定为什么这不起作用,但与我的其他viewcontroller一起工作。我一定错过了一些小细节。

AccountViewController.h

@protocol AccountViewControllerDelegate;
@interface AccountViewController : UIViewController{

}
@property (nonatomic, assign) id <AccountViewControllerDelegate> accountViewDelegate;
@end

@protocol AccountViewControllerDelegate <NSObject>
- (void)showLabel;
@end

AccountViewController.m

-(IBAction)save:(id)sender {
    [self showLabel];
}

- (void)showLabel {
    if (self.accountViewDelegate) {
        NSLog(@"showlabel");

        [self.accountViewDelegate showLabel];
    }
}

MapViewController.m

-(void)showLabel {
    NSLog(@"SHOW");
}

3 个答案:

答案 0 :(得分:3)

您没有显示将MapViewController指定为AccountViewController的委托的位置。也许那就是你缺少的东西

//(from somewhere in the MapViewController)

AccountViewController *accountVC = //however you instantiate it (segue, storyboard etc
accountVC.accountViewDelegate = self;

答案 1 :(得分:1)

请注意,代表不应该有强烈的参考。

所以使用

@property (unsafe_unretained) id <AccountViewControllerDelegate> accountViewDelegate;

现在MapViewController.mMapViewController.h符合此协议

@interface MapViewController : UIViewController <AccountViewControllerDelegate>{

}

然后在MapViewController.m

AccountViewController *accountVC = [[AccountViewController alloc]init]; // initialize it with whatever be like storyboard or nib
accountVC.accountViewDelegate = self;

您的AccountViewController.h文件应如下所示

@protocol AccountViewControllerDelegate <NSObject>
 - (void)showLabel;
@end

@interface AccountViewController : UIViewController{

}
@property (unsafe_unretained) id <AccountViewControllerDelegate> accountViewDelegate;
@end

答案 2 :(得分:0)

这是您在不同文件中应该拥有的内容:

<强> AccountViewController.h

请注意,“assign”主要用于NSInteger,CGFloat,BOOL等原语(即,对于非对象的属性)。使用“弱”来指向你的代表而不增加他的保留计数。

@protocol AccountViewControllerDelegate;

@interface AccountViewController : UIViewController
@property (nonatomic, weak) id <AccountViewControllerDelegate> accountViewDelegate;
@end

@protocol AccountViewControllerDelegate <NSObject>
- (void)showLabel;
@end

<强> AccountViewController.m

在这里,通常最好检查代理是否不是nil,以及是否有您要调用的方法。请使用respondToSelector

-(IBAction)save:(id)sender {
    [self showLabel];
}

- (void)showLabel {
    if (self.accountViewDelegate && [self.accountViewDelegate respondsToSelector:@selector(showLabel)]) {
        NSLog(@"showlabel");

        [self.accountViewDelegate showLabel];
    }
}

<强> MapViewController.h

请务必在此处导入"AccountViewController.h"

#import "AccountViewController.h"
@interface MapViewController : UIViewController <AccountViewControllerDelegate>
@end

<强> MapViewController.m

将以下内容放在您实例化AccountViewController对象的位置:

//Somewhere
AccountViewController *accountViewController = [[AccountViewController alloc] init];
accountViewController.accountViewDelegate = self;

这是你的委托方法实现:

- (void)showLabel {
    NSLog(@"SHOW");
}