将C++类的实例转换为NSObject,然后添加到NSMutableArray

Pav*_*van 1 c++ cocoa-touch objective-c objective-c++ nsmutablearray

这是一个用C++创建的简单类,用于为iOS设备创建的音乐应用程序,它将存储一些音符值及其时间:

class info {
public:
    float attackTime;
    Note noteStriked;

    void setData(float timeOfAttack, Note nameOfStrikeNote){
        attackTime = timeOfAttack;
        noteStriked = nameOfStrikeNote;
    }
};
Run Code Online (Sandbox Code Playgroud)

以上...注意是一个只能包含{SNARE,DRUM,HIHAT}等默认值的结构.我们的想法是创建一个Note对象并将这些对象存储在NSMutableArray中以供以后访问.

然后在我的主.h文件中,我有一个NSMutableArray sequenceOfNotes; 在我的.m文件中,我试图将一个对象添加到我的mutablearray ...但我不知道该怎么做.我尝试了各种各样的东西,但失败了它不起作用!

//Create one instance of the class
NoteData *currentNoteData;

// Update the instance of the class.. its two variables: attackTime and noteStriked
currentNoteData->attackTime = timeHit;
currentNoteData->noteStriked = SNARE;

//Then im trying to add the above instance to my mutableArray below
[sequenceOfNotes addObject:currentNoteData];
Run Code Online (Sandbox Code Playgroud)

在该行上产生的错误是无法初始化类型为'id'的参数,其值为'NoteData*'的左值

修复错误之后喜欢做的是能够在我选择的数组的任何位置检索我的对象,然后能够在该特定索引处从该对象中选择属性变量.

//PsuedoCode
array {
  position 0: NoteData object {
                attackTime = 45.34,
                noteStriked = HIHAT
              }
  position 1: NoteData object {
                attackTime = 65.32,
                noteStriked = SNARE
              }
  position 2: NoteData object {
                attackTime = 78.53,
                noteStriked = HIHAT
              }
  position 3: NoteData object {
                attackTime = 98.44,
                noteStriked = KICK
              }
  etc etc

}

//and then convert NSObject to normal c++ object something like this... 
NoteData temp = [noteSequence objectAtIndex:0];

//so that i can then do this:
float currentTime = temp.attackTime;
Note currentNote = temp.noteStriked;
Run Code Online (Sandbox Code Playgroud)

显然是一个转换问题..如果有人可以帮助我这将是非常棒的

Ric*_*III 8

您必须将C++对象指针包装到NSValue中:

[MyArray addObject:[NSValue valueWithPointer:new MyCPPObject()]];

...

MyCPPObject *obj = [[MyArray objectAtIndex:index] pointerValue];
Run Code Online (Sandbox Code Playgroud)

或者,你为什么不只使用一个vector<MyCPPObject>或一个list<MyCPPObject>