我想用开关(来自菜单类)启动/停止计时器(在主类中),根据我的代码,当开关打开时定时器启动,当我关闭开关时定时器不停止。这是我的代码:
menu.h
@protocol FlipsideViewControllerDelegate;
@interface FlipsideViewController : UIViewController {
id <FlipsideViewControllerDelegate> delegate;
IBOutlet UISwitch *fireSwitch;
}
@property (assign)UISwitch* fireSwitch;
-(IBAction)autoFire;
menu.m
#import "FlipsideViewController.h"
#import "mainViewController.h"
@synthesize fireSwitch;
- (void)viewDidLoad
{
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
//[super viewDidLoad];
fireSwitch.on = [defs boolForKey:activateautoplay];
}
-(IBAction)autoFire {
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
[defs setBool:fireSwitch.on forKey:activateautoplay];
[[NSUserDefaults standardUserDefaults] synchronize];
}
Main.h
#import "FlipsideViewController.h"
#define activateautoplay @"isactivateautoplay"
@interface mainViewController : UIViewController <FlipsideViewControllerDelegate> {
NSTimer *Autotimer;
}
-(void)updateImagePosition:(NSTimer*)mytimer;
的main.m
#import "mainViewController.h"
@sunthesize Autotimer;
- (void)awakeFromNib {
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
if ([defs boolForKey:activateautoplay]) {
self.Autotimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateImagePosition:) userInfo:nil repeats:YES];
} else {
[self.Autotimer invalidate];
}
}
-(void)updateImagePosition:(NSTimer*)mytimer {
.....
}
答案 0 :(得分:1)
如果您不介意在两个类之间引入耦合,您可以随时向FlipsideViewController提供对mainViewController的引用,并让它直接引用方法。或者,您可以让FlipsideViewController在更改值时向其委托发送相应的消息,然后可以调用mainViewController。
但从避免不必要耦合的角度来看,最好的方法是让mainViewController监听NSUserDefaultsDidChangeNotification
,这会在调用setBool:forKey:
时自动发送。
请求编辑:
在Main.m中,添加如下方法:
- (void)startOrStopTimer {
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
if ([defs boolForKey:activateautoplay]) {
if (!self.Autotimer) self.Autotimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateImagePosition:) userInfo:nil repeats:YES];
} else {
[self.Autotimer invalidate];
self.Autotimer = nil;
}
}
然后将awakeFromNib
更改为以下内容:
- (void)awakeFromNib {
[self startOrStopTimer];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startOrStopTimer) name:NSUserDefaultsDidChangeNotification object:nil];
}
请务必将其添加到dealloc
:
[[NSNotificationCenter defaultCenter] removeObserver:self];
FlipsideViewController不需要进行任何更改,也不需要设置包。