在Objective-C中预处理循环

Mou*_*ach 5 algorithm optimization objective-c

我目前正在编写一个程序来帮助我控制复杂的灯光安装.我的想法是告诉程序启动预设,然后应用程序有三个选项(取决于预设类型)

1)灯光进入一个位置(所以当预设开始时只发送一组数据)2)灯光遵循一个数学方程式(例如:带有计时器的正弦曲线,以制作光滑的圆圈)3)灯光响应流量数据(ex midi控制器)

所以我决定使用一个我称之为AppBrain的对象,它从控制器和模板接收数据,但也能够将处理后的数据发送到灯光.

现在,我来自非本地编程,我有一些信任问题涉及处理大量处理,事件和时间; 以及理解100%Cocoa逻辑的麻烦.

这是实际问题开始的地方,抱歉

我想要做的是,当我加载预设时,我会解析它以准备定时器/数据接收事件,因此它不必每秒100次通过100个灯的每个选项.

为了更深入地解释,这里是我将如何在Javascript中做到这一点(当然,糟糕的伪代码)

var lightsFunctions = {};

function prepareTemplate(theTemplate){
    //Let's assume here the template is just an array, and I won't show all the processing

    switch(theTemplate.typeOfTemplate){
        case "simpledata":
            sendAllDataTooLights(); // Simple here
            break;

        case "periodic":


               for(light in theTemplate.lights){

                    switch(light.typeOfEquation){
                        case "sin":
                            lightsFunctions[light.id] = doTheSinus; // doTheSinus being an existing function
                            break;

                        case "cos":

                            ...
                     }
                }


               function onFrame(){
                    for(light in lightsFunctions){
                        lightsFunctions[light]();
                    }
               }

                var theTimer = setTimeout(onFrame, theTemplate.delay);

                break;

            case "controller":

                //do the same pre-processing without the timer, to know which function to execute for which light

                break;

    }


    }

}
Run Code Online (Sandbox Code Playgroud)

所以,我的想法是在NSArray中存储我需要的处理函数,所以我不需要在每个帧上测试类型并且耗费一些时间/ CPU.

我不知道我是否清楚,或者我的想法是否可行/是好的方法.我主要是在寻找算法的想法,如果你有一些代码可以指导我的方向......(我知道PerformSelector,但我不知道它是否适合这种情况.

谢谢;

一世_

Kru*_*lur 4

首先,不要花时间优化你不知道的性能问题。该类型的 100 次迭代在原生世界中不算什么,即使在较弱的移动 CPU 上也是如此。

现在,解决你的问题。我认为您正在编写某种配置/DSL 来指定灯光控制序列。一种方法是将存储在您的NSArray. 块相当于 JavaScript 中的函数对象。例如:

typedef void (^LightFunction)(void);

- (NSArray*) parseProgram ... {
    NSMutableArray* result = [NSMutableArray array];
    if(...) {
        LightFunction simpledata = ^{ sendDataToLights(); };
        [result addObject:simpleData];
    } else if(...) {
        Light* light = [self getSomeLight:...];
        LightFunction periodic = ^{
            // Note how you can access the local scope of the outside function.
            // Make sure you use automatic reference counting for this.
            [light doSomethingWithParam:someParam];
        };
        [result addObject:periodic];
    }
    return result;
}
...
NSArray* program = [self parseProgram:...];

// To run your program
for(LightFunction func in program) {
    func();
}
Run Code Online (Sandbox Code Playgroud)