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

convert instance of C++ class to NSObject and then add to NSMutableArray

本文关键字:然后 添加 NSMutableArray NSObject C++ 实例 转换 将类      更新时间:2023-10-16
这是一个

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

class info {
public:
    float attackTime;
    Note noteStriked;
    void setData(float timeOfAttack, Note nameOfStrikeNote){
        attackTime = timeOfAttack;
        noteStriked = nameOfStrikeNote;
    }
};

以上。。。注意是一个结构,它只能包含默认值,如{军鼓,鼓,HIHAT}等。这个想法是创建一个 Note 对象并将这些对象存储在 NSMutableArray 中以供以后访问。

然后在我的主 .h 文件中,我有一个 NSMutableArray sequenceOfNotes;在我的 .m 文件中,我正在尝试将一个对象添加到我的可变数组中......但我不知道该怎么做。我尝试了各种事情,但失败了,它不起作用!

//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];

该行产生的错误是无法使用类型为"NoteData *"的左值初始化类型为"id"的参数

修复

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

//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;

显然有一个转换问题..如果有人可以帮助我解决这个问题,那就太棒了

您必须将

C++对象指针包装到 NSValue 中:

[MyArray addObject:[NSValue valueWithPointer:new MyCPPObject()]];
...
MyCPPObject *obj = [[MyArray objectAtIndex:index] pointerValue];

或者,您为什么不只使用vector<MyCPPObject>list<MyCPPObject>