将代码转换为函数

Posted

技术标签:

【中文标题】将代码转换为函数【英文标题】:Convert code to function 【发布时间】:2010-10-04 19:16:27 【问题描述】:

大家好,我需要将此代码转换为具有 2 个参数的函数,在这种情况下,第一个参数是 News,第二个参数是 aif 你可以这样做吗?

-(IBAction)news

CFURLRef        soundFileURLRef;
SystemSoundID   soundFileObject;
CFBundleRef mainBundle;
mainBundle = CFBundleGetMainBundle ();

// Get the URL to the sound file to play
soundFileURLRef  =  CFBundleCopyResourceURL (mainBundle,
                                             CFSTR ("News"),
                                             CFSTR ("aif"),
                                             NULL);

// Create a system sound object representing the sound file
AudioservicesCreateSystemSoundID (soundFileURLRef, &soundFileObject);

AudioServicesPlaySystemSound (soundFileObject);

return;

【问题讨论】:

【参考方案1】:

如果 CFSTR 是问题所在,那么解决方案是:

-(void) playNews: (NSString*) news type: (NSString*) type

    CFURLRef        soundFileURLRef;
    SystemSoundID   soundFileObject;
    CFBundleRef mainBundle;
    mainBundle = CFBundleGetMainBundle ();

    // Get the URL to the sound file to play
    soundFileURLRef  =  CFBundleCopyResourceURL (mainBundle,
            (CFStringRef)news,
            (CFStringRef)type,
            NULL);

    // Create a system sound object representing the sound file
    AudioServicesCreateSystemSoundID (soundFileURLRef, &soundFileObject);

    AudioServicesPlaySystemSound (soundFileObject);

但是 (IBAction) 声明在这里没有意义,因为这个方法不能直接从 Interface Builder 中使用。

【讨论】:

你好,谢谢你的回答,这就是我想要的,但是当我写 PlayNews:@"news1" ofType:@"wav"; xcode给我一个错误:预期的';'在'type'之前你能帮我解决这个问题吗 需要放在尖括号中:[obj playNews:@"news" ofType:@"wav"];【参考方案2】:

如果这是一个类从使用控件的用户那里收到的操作,那么您唯一能做的就是-(IBAction)nameOfAction:(id)sender;。否则,您需要编写命令来获取您需要的两个参数并从IBAction 调用它。

【讨论】:

以上是关于将代码转换为函数的主要内容,如果未能解决你的问题,请参考以下文章

将功能组件代码转换为类组件代码

如何将此 Java 代码转换为 kotlin 代码

将函数指针的 C 结构体转换为 JNA 代码

将 python、numpy 和 scipy 代码转换为 C++ 兼容代码?

如何使用 matlab 编码器将 matlab 函数“pchip”转换为 c 代码

将 SSE 矩阵向量乘法代码转换为 AVX