You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用NSTimer定时拍照,第11次停止后无法跳转页面求助

问题排查与修复方案

嘿,我来帮你搞定这个第11次拍照后无法跳转的问题!先梳理下几个最可能的原因,以及对应的修复方法:

1. 变量名笔误(最容易踩的坑)

看你代码里的细节:

currenPageNumber +=1; // 这里少了个't',写成curren而不是current
// ...
if (currentCount == 11){ // 这里判断的是currentCount

如果currenPageNumber和currentCount本来是同一个计数变量,那currentCount根本没被递增,永远到不了11,跳转逻辑自然不会执行!先把变量名统一,比如都改成currentCount:

currentCount +=1;
// ...
if (currentCount == 11){

2. Timer初始化的冗余嵌套

你初始化Timer的代码套了两层dispatch_async,其实完全没必要——scheduledTimerWithTimeInterval默认就是在当前线程的RunLoop里启动Timer,而且你最终也切到了主队列,所以可以简化成:

// 直接在主队列创建Timer(如果初始化代码本身就在主队列,连这层dispatch都可以省)
dispatch_async(dispatch_get_main_queue(), ^{
    _photoTimer = [NSTimer scheduledTimerWithTimeInterval:24.5 target:self selector:@selector(takePhotos) userInfo:nil repeats:YES];
});

3. 跳转时NavigationController可能为nil

如果当前VC不是被UINavigationControllerpush进来的,而是被present过来的,那self.navigationController就是空的,这时候调用它的presentViewController会直接失败。可以做个兼容:

UploadVC * uploadVC = [self.storyboard instantiateViewControllerWithIdentifier:@"UploadVC"];
// 先判断导航控制器是否存在,不存在就直接用当前VC present
if (self.navigationController) {
    [self.navigationController presentViewController:uploadVC animated:YES completion:nil];
} else {
    [self presentViewController:uploadVC animated:YES completion:nil];
}

4. 计数变量的线程安全问题

currentCount是在全局队列(子线程)里递增的,如果它是普通的实例变量,没有做线程同步,可能会出现计数错误(比如多次递增只生效一次),导致永远触发不了第11次的判断。可以给它加个锁,或者声明成原子属性:

// 方案1:声明为原子属性
@property (atomic, assign) NSInteger currentCount;

// 方案2:递增时加锁
@synchronized(self) {
    currentCount +=1;
}

修复后的完整takePhotos示例

-(void)takePhotos{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //taking photos....
        // 线程安全地递增计数
        @synchronized(self) {
            self.currentCount +=1;
        }
        
        dispatch_async( dispatch_get_main_queue(), ^{
            //showing photos
        });
        
        dispatch_async( dispatch_get_main_queue(), ^{
            if (self.currentCount == 11){
                [_photoTimer invalidate];
                _photoTimer = nil;
                UploadVC * uploadVC = [self.storyboard instantiateViewControllerWithIdentifier:@"UploadVC"];
                // 兼容导航控制器的情况
                if (self.navigationController) {
                    [self.navigationController presentViewController:uploadVC animated:YES completion:nil];
                } else {
                    [self presentViewController:uploadVC animated:YES completion:nil];
                }
            }
        });
    });
}

内容的提问来源于stack exchange,提问作者Satty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:08:53