我正在使用iOS应用程序,该应用程序具有.mm格式的文件,并且完全包含用C编写的代码。我需要将以下代码块放入此文件中:

void initAudioSession()
{
    BOOL success = NO;
    NSError *error = nil;

    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:&error];


//the above code is the method where the block below goes in

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioSessionDidChangeInterruptionType:)
     name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];


依次调用以下方法:

- (void)audioSessionDidChangeInterruptionType:(NSNotification *)notification
{
    AVAudioSessionInterruptionType interruptionType = [[[notification userInfo]
    objectForKey:AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
    if (AVAudioSessionInterruptionTypeBegan == interruptionType)
    {
    }
    else if (AVAudioSessionInterruptionTypeEnded == interruptionType)
    {
    }
}


我上面发布的两个代码块都在Objective-C中,我需要将它们都转换为C,然后将它们放在.mm文件中。问题是我没有C语言背景,并且不确定执行此操作需要进行哪些更改。我遇到的一个明显问题是编译器无法识别关键字self。为什么不能识别self,在C语言中应将其更改为什么?

最佳答案

要用C语言编写Objective-C代码,您必须使用Objective-C的C API,标头可以找到为<objc/objc.h><objc/runtime.h><objc/message.h>。您可以使用sel_registerName调用从objc_msgSend获取的选择器,并使用objc_getRequiredClassobjc_getClass获取类。请注意,我列出了最容易使用的功能,其中包含使Objective-C工作所需的所有功能。

这是这种风格的第二个代码块。魔幻数字在C不能读取的头文件中找到。还要注意,由于值缓存和类似的事情,从Objective-C代码编译的代码可能会更高效。

extern id *const AVAudioSessionInterruptionTypeKey;
void audioSessionDidChangeInterruptionType(id self, SEL _cmd, id notification) {
    SEL userInfo = sel_registerName("userInfo");
    SEL objectForKey = sel_registerName("objectForKey:");
    SEL unsignedIntegerValue = sel_registerName("unsignedIntegerValue");
    id tmpid = objc_msgSend(notification, userInfo);
    tmpid = objc_msgSend(tmpid, objectForKey, AVAudioSessionInterruptionTypeKey);
    unsigned interruptionType = objc_msgSend(tmpid, unsignedIntegerValue);
    if (interruptionType == 1) {
        // AVAudioSessionInterruptionTypeBegan
    } else {
        // AVAudioSessionInterruptionTypeEnded
    }
}


可能值得检查您的代码是否可以移植到apples C音频API CoreAudio,它可能比任何C转换都要好。

关于ios - 需要将方法从Objective-C转换为iOS中的C,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26773667/

10-14 20:59
查看更多