这是一个用C ++创建的简单类,用于为iOS设备创建的音乐应用程序,它将存储一些音符值及其时间:
class info {
public:
float attackTime;
Note noteStriked;
void setData(float timeOfAttack, Note nameOfStrikeNote){
attackTime = timeOfAttack;
noteStriked = nameOfStrikeNote;
}
};
上面...注意是一个只能包含{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];
该行产生的错误是 无法使用“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;
显然是一个转换问题..如果有人可以帮助我,这将是非常棒的
答案 0 :(得分:8)
您必须将C ++对象指针包装到NSValue中:
[MyArray addObject:[NSValue valueWithPointer:new MyCPPObject()]];
...
MyCPPObject *obj = [[MyArray objectAtIndex:index] pointerValue];
或者,为什么不使用vector<MyCPPObject>
或list<MyCPPObject>
?