'self' 不是有效目标。混合 Objective-C 和 C++ (Objective-C++)

'self' is not a valid target. Mixing Objective-C and C++ (Objective-C++)

我在混合 C++ 和 Objective-C(实际上是 Objective-C++)方面取得了一些进展,但现在我被卡住了。

我目前的问题是 Objective-C 'self' 变量似乎不正确并在我的代码中抛出异常:

Exception: Invalid parameter not satisfying: target

我假设是指 selfRef 不是有效目标:

addTarget:selfRef

初始化 'self' 并使其可用于 C++ 函数的正确方法是什么。

这是我接触 objective-c/objective-c++ 的第一天,如果这可能是初级的,请原谅 ;)

代码:

#import "ios_objc.h"
#import <Foundation/Foundation.h>
#import <AVFoundation/AVAudioSession.h>
#import <MediaPlayer/MediaPlayer.h>
#import <MediaPlayer/MPRemoteCommandCenter.h>

id selfRef;
//static Ios_objc *selfRef; //I tried this as well.

@implementation Ios_objc

IosImpl::IosImpl(void) //: self( NULL )
{

}

IosImpl::~IosImpl(void)
{
    [Ios_objc dealloc];
}

void IosImpl::init(void)
{
    selfRef = [[Ios_objc alloc] init];
}

void IosImpl::enable(void)
{
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

    MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
    commandCenter.playCommand.enabled = YES;

    @try {
        [commandCenter.playCommand addTarget:selfRef action:@selector(playSounds)];
    }
    @catch (NSException *exception) {
        NSLog(@"Exception: %@", exception.reason);
    }

    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}

void IosImpl::playSounds()
{
        NSLog(@"Play");
}

//I also tried 'Objective-C' style function signature.
//- (void) playSounds
//{
//
//}

@end

我相信异常来自 -[MPRemoteCommand addTarget:action:] 实现中的语句,看起来像:

NSParameterAssert(target);

也就是说,它正在验证它收到的 target 参数是非 nil。这就是奇怪的措辞“……参数不满足:目标”的原因。 "target"为实际测试条件,参数不满足。如果语句写成 NSParameterAssert(target != nil);,那么异常原因会是“...参数不满足:target != nil”,这样会更清楚。

无论如何,您在 IosImpl::init() 中向 selfRef 写入了一个(大概是非 nil)值,但这叫什么?构造函数并不像当前编写的那样。从构造函数中调用 init() 或直接将该代码放入构造函数中。

此外,您的析构函数不正确。正如目前所写的那样,它在 Ios_objc class 对象上调用 -dealloc,这不太可能做任何事情(而且,如果做了,也没什么好处)。您的意思可能是 [selfRef release]注意: release,而不是 dealloc)。一般来说,你不应该调用 -dealloc 除非在你自己的 -dealloc 方法的实现中调用 super