我有2个UIViewControllers,GameController和RhythmController。 我在 RhythmController.h 中定义了RhythmDelegate。 RhythmController中的doEndGame方法应该在GameController gameOver中调用委托方法,该方法实现了委托协议。
我无法理解为什么这不起作用...我的代码是错误的吗? 在此先感谢您的帮助。
@class RhythmView,RhythmDelegate, RhythmController;
@protocol RhythmDelegate
@required
-(void)gameOver:(RhythmController*)aRhythmController;
@end
@interface RhythmController : UIViewController <UIGestureRecognizerDelegate, UIAlertViewDelegate> {
.....
}
@property (nonatomic, retain) IBOutlet NSObject<RhythmDelegate>* delegate;
在RhythmController.m中,我的委托调用如下:
@implementation RhythmController
@synthesize delegate;
-(void)doEndGame{
isPaused = true;
[delegate gameOver:self];
}
我确认在内部使用断点调用doEndGame。但是,它没有转到GameController中我想要的方法,它实现了委托。
#import <UIKit/UIKit.h>
#import "CoinsController.h"
#import "CoinsGame.h"
#import "HighscoreController.h"
#import "RhythmController.h"
#import "RhythmView.h"
@interface GameController : UIViewController <RhythmDelegate> {
IBOutlet UIView *landscapePlayView;
IBOutlet UIView *landscapeGameHolderView;
IBOutlet UIView *portraitPlayView;
IBOutlet UIView *portraitGameHolderView;
IBOutlet UIView *loadingView;
IBOutlet UIView *welcomeView;
IBOutlet UIButton *continueButton;
IBOutlet UIView *aboutView;
IBOutlet UIView *playView;
IBOutlet UIView *rhythmView;
//IBOutlet UIView *levelSelectView;
IBOutlet UILabel *musicNotation;
IBOutlet CoinsController *coinsController;
IBOutlet RhythmController *rhythmController;
IBOutletCollection(UILabel) NSArray *remainingTurnsLabels;
IBOutletCollection(UILabel) NSArray *scoreLabels;
IBOutlet HighscoreController *highscoreController;
CoinsGame* previousGame;
BOOL isPlayingGame;
}
-(void)setPreviousGame:(CoinsGame*)aCoinsGame;
-(CoinsGame*)currentGame;
- (IBAction)continueGameClicked:(id)sender;
- (IBAction)newGameClicked:(id)sender;
- (IBAction)highScoresClicked:(id)sender;
- (IBAction)aboutClicked:(id)sender;
- (IBAction)aboutDoneClicked:(id)sender;
- (IBAction)highscoreDoneClicked:(id)sender;
-(void)loadImages;
-(void)showPlayView: (UIInterfaceOrientation)interfaceOrientation;
-(void)doPause;
@end
在GameController.m中,方法是
// RhythmDelegate Tasks
-(void)gameOver:(RhythmController*)aRhythmController{
NSLog(@"Came into gameOver delegated task");
[self.view addSubview: welcomeView];
}
答案 0 :(得分:2)
检查您的委托变量在断点处是否为零。如果是,那么你忘了设置代表。
您可以在创建RhythmController之后在gamecontroller的viewdidload方法中轻松设置它:
rythmcontroller.delegate = self;
答案 1 :(得分:1)
您可能忘记将GameController
实例设置为RhythmController
的代理人。简单地为代表实现协议并不会神奇地建立委托连接。你需要这样的一条线:
myRhythmController.delegate = myGameController;
作为备注:代表通常是weak
引用,或assign
属性。这是为了防止委托对象和原始对象之间的保留循环
答案 2 :(得分:1)
您是否忘记为rhythmController实例设置委托属性?
如果您已经创建了代码,那么您可以这样做:
rhythmController = [[RhythmController alloc] init];
rhythemController.delegate = self;
...
[rhythmController release];
其中“self”是GameController实例。