第一個viewcontroller是排行榜菜單,裡面有一個按鈕指示到第二個viewcontroller中,第二個是小游戲,如果玩家輸了,最高分變動,就更新排行榜。在玩家完成游戲時建了帶兩個按鈕的UIAlertView,一個是主菜單,另一個是重新開始,我的代碼如下:我想通過delegation更新排行榜
@protocol highScoreProtocol <NSObject>
-(void)updateHighScore:(int) score;
@end
@interface ViewController : UIViewController <UIAlertViewDelegate>
@property (nonatomic) int score;
@property (nonatomic, weak) id <highScoreProtocol> delegateHighScore;
@implementation ViewController
@synthesize score=_score;
@synthesize delegateHighScore=_delegateHighScore;
-(void)lostGame{
[self.delegateHighScore updateHighScore:self.score];
UIAlertView *losingScreen=[[UIAlertView alloc]initWithTitle:@"Game Over" message:[NSString stringWithFormat:@"Your Score Is %d", self.score] delegate:self cancelButtonTitle:@"Main Menu" otherButtonTitles:@"Restart", nil];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex==0) {
} else if (buttonIndex==1){
}
}
@end
@interface MenuVC : UIViewController <highScoreProtocol>
@property (weak, nonatomic) IBOutlet UILabel *labelHighScore;
@end
@implementation MenuVC
- (void)viewDidLoad
{
[super viewDidLoad];
ViewController *vc=[[ViewController alloc]init];
vc.delegateHighScore=self;
}
-(void)updateHighScore:(int)score{
if (score>[self.labelHighScore.text integerValue]) {
self.labelHighScore.text=[NSString stringWithFormat:@"%d", score];
}
NSLog(@"does this method even run");
}
不知道哪出錯了,希望大家幫忙。
這行代碼不對
ViewController *vc=[[ViewController alloc]init];
vc.delegateHighScore=self;
定義了一個新的不相干的viewcontroller。
如果你的情況是這樣:定義一個viewcontroller的identifier,選擇viewcontroller,……
然後用這行代碼:
ViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"yourIdentifier"];
vc.delegateHighScore = self;