我有一个非常基本的应用程序,如果“if”语句的条件为真,则在其中实例化第二个 ViewController。加载第二个 ViewController 后,第一个 ViewController 的方法仍然运行。我需要停止所有以前的方法以使应用程序正确运行。
// 在 FirstViewController.h 中
#import <UIKit/UIKit.h>
@interface FirstViewController : UIViewController
{
NSTimeInterval beginTouchTime;
NSTimeInterval endTouchTime;
NSTimeInterval touchTimeInterval;
}
@property (nonatomic, readonly) NSTimeInterval touchTimeInterval;
- (void) testMethod;
@end
// 在 FirstViewController.m 中
#import "FirstViewController.h"
#import "SecondViewController.h"
@implementation FirstViewController
@synthesize touchTimeInterval;
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void) testMethod
{
if (touchTimeInterval >= 3)
{
NSLog(@"Go to VC2");
SecondViewController *secondBViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"];
[self presentViewController:secondViewController animated:YES completion:nil];
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
beginTouchTime = [event timestamp];
NSLog(@"Touch began");
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
endTouchTime = [event timestamp];
NSLog(@"Touch ended");
touchTimeInterval = endTouchTime - beginTouchTime;
NSLog(@"Time interval: %f", touchTimeInterval);
[self testMethod]; // EDIT: USED TO BE IN viewDidLoad
}
@end
第二个屏幕成功加载,但日志消息仍然存在,这意味着 FirstViewController 的方法仍然存在,尽管在 SecondViewController 的视图中。我究竟做错了什么?