c++ - 从后台线程错误修改自动布局引擎,来自 C++

标签 c++ objective-c xcode boost-asio djinni

当通过双向 djinni 架构从 C++ 进行 UI 调用时,我在 Xcode 7.1 中遇到以下错误:

此应用程序正在从后台线程修改自动布局引擎,这可能会导致引擎损坏和奇怪的崩溃。这将在未来的版本中导致异常。

我能够使用此处给出的解决方案解决 Objective-C 中的问题:

Getting a “This application is modifying the autolayout engine” error?

dispatch_async(dispatch_get_main_queue(), ^{
    // code here
});

我的问题是,有没有一种方法可以在 C++ 中以某种方式完成此操作,而不必在每次调用 UI 时都调用 Objective-C 中的 dispatch_async?还是就 Xcode 而言,来自 C++ 的每个调用都被视为后台线程?


发布省略自动生成源文件的相关代码,完整项目也可在 github 上获得:

cpptimer.djinni:

timer = interface +c {
    static create_with_listener(listener: timer_listener): timer;
    start_timer(seconds: i32);
}

timer_listener = interface +j +o {
    timer_ticked(seconds_remaining: i32);
    timer_ended();
}

timer_impl.hpp

#pragma once

#include <boost/asio.hpp>

#include "timer.hpp"
#include "timer_listener.hpp"

namespace cpptimer {

    class TimerImpl : public Timer {

    public:

        TimerImpl(const std::shared_ptr<TimerListener> & listener);

        void StartTimer(int32_t seconds);

    private:

        void TimerTick(const boost::system::error_code& e);

        std::shared_ptr<TimerListener> listener_;

        boost::asio::io_service io_service_;
        boost::asio::deadline_timer timer_;
        int time_remaining_;

    };

}

timer_impl.cpp

#include <boost/bind.hpp>
#include <boost/thread.hpp>

#include "timer_impl.hpp"

namespace cpptimer {

    std::shared_ptr<Timer> Timer::CreateWithListener(const std::shared_ptr<TimerListener> & listener) {
        return std::make_shared<TimerImpl>(listener);
    }

    TimerImpl::TimerImpl(const std::shared_ptr<TimerListener> & listener):
            io_service_(),
            timer_(io_service_, boost::posix_time::seconds(1)) {
        listener_ = listener;
    }

    void TimerImpl::StartTimer(int32_t seconds) {
        time_remaining_ = seconds;
        io_service_.reset();
        timer_.async_wait(boost::bind(&TimerImpl::TimerTick, this, boost::asio::placeholders::error));
        boost::thread th([&] { io_service_.run(); });
    }

    void TimerImpl::TimerTick(const boost::system::error_code& e) {
        if(e != boost::asio::error::operation_aborted) {
            time_remaining_--;
            std:: cout << "C++: TimerTick() with " << std::to_string(time_remaining_) << " seconds remaining.\n";
            if (time_remaining_ > 0) {
                timer_.expires_from_now(boost::posix_time::seconds(1));
                timer_.async_wait(boost::bind(&TimerImpl::TimerTick, this, boost::asio::placeholders::error));
                listener_->TimerTicked(time_remaining_);
            } else {
                listener_->TimerEnded();
            }
        }
    }

}

ViewController.h

#import <UIKit/UIKit.h>

#import "CPPTTimerListener.h"

@interface ViewController : UIViewController<CPPTTimerListener>

@property (nonatomic, strong) IBOutlet UILabel *timerLabel;

@end

ViewController.m

#import "ViewController.h"
#import "CPPTTimer.h"

@interface ViewController () {
    CPPTTimer *_timer;
}

@end

@implementation ViewController

@synthesize timerLabel;

- (void)viewDidLoad {

    [super viewDidLoad];

    // initialize the timer
    _timer = [CPPTTimer createWithListener:self];

    // start a 5 second timer
    [_timer startTimer:5];

}

# pragma mark CPPTTimerListener methods

- (void)timerEnded {
    NSLog(@"Obj-C: timerEnded.");
}

- (void)timerTicked:(int32_t)secondsRemaining {
    NSLog(@"Obj-C: timerTicked with %d seconds remaining.", secondsRemaining);
    // without dispatch_async, background thread warning is thrown
    dispatch_async(dispatch_get_main_queue(), ^{
        timerLabel.text = [NSString stringWithFormat:@"%d", secondsRemaining];
    });
}

@end

最佳答案

对 UI 类的所有访问必须发生在主线程上。您的升压计时器不在主线程上运行。

因此,让您的计时器在主线程上触发可能是有意义的。您可以使用标准的 libdispatch API,即使是纯 C++ 代码(不必是 .mm ObjC++)。

一定要加上#include <dispatch/dispatch.h>到您的 CPP 实现文件。

以下代码更改将确保计时器始终在 Cocoa 主线程上运行。

void TimerImpl::TimerTick(const boost::system::error_code& e) {
    if(e != boost::asio::error::operation_aborted) {
        time_remaining_--;
        std:: cout << "C++: TimerTick() with " << std::to_string(time_remaining_) << " seconds remaining.\n";

        if (time_remaining_ > 0) {
            timer_.expires_from_now(boost::posix_time::seconds(1));
            timer_.async_wait(boost::bind(&TimerImpl::TimerTick, this, boost::asio::placeholders::error));

            auto listener = listener_;
            auto time_remaining = time_remaining_;
            dispatch_async(dispatch_get_main_queue(), ^{
               listener->TimerTicked(time_remaining);
            });
        } else {
            auto listener = listener_;
            dispatch_async(dispatch_get_main_queue(), ^{
                listener->TimerEnded();
            });
        }
    }
}

我假设该代码的其余部分有效。我所做的只是修改调用回调的方式。请注意,我们创建了 listener_ 的拷贝shared_ptrtime_remaining_值(value)。这些将被在主线程上执行的 block 捕获(并复制)。

如果你能保证this在该 block 执行之前不会删除,那么您可以隐式捕获 this ...

dispatch_async(dispatch_get_main_queue(), ^{
   listener_->TimerTicked(time_remaining_);
});

或者,如果您启用 shared-from-this,您可以创建指向 this 的共享指针的拷贝并以这种方式捕获它...

auto self = shared_from_this();
dispatch_async(dispatch_get_main_queue(), ^{
   self->listener_->TimerTicked(self->time_remaining_);
});

有很多方法可以做到这一点,但这可能是最简单的,现在您要确保所有计时器都触发 Cocoa 主线程。

关于c++ - 从后台线程错误修改自动布局引擎,来自 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33656144/

相关文章:

ios - iOS 上带有刻度线的水平 slider

android - 如何让手机从 Qt Android 振动

ios - Swift Var 中使用的数据结构和 var 到类型的内部映射

iphone - 如何判断正在运行的场景是什么样的类/场景?

objective-c - 在 ocUnit 中比较 NSArray

ios - 如何将动态字符串传递给 PushNotificationManager

c++ - 在 xcode 中使用 ITK

c++ - 在 lambda 中捕获命名空间变量

c++ - 函数中的条件 cv 限定符

c++ - std::vector 保留方法无法分配足够的内存