2013-10-07 32 views
1

我一直在試圖調用下面的函數。似乎只要在函數playNote我試圖訪問我作爲參數傳遞的對象( myNum)它總是崩潰。我很新,我可能不明白如何通過CCCallFuncND傳遞參數。所有意見都表示讚賞。Objective C - CCCallFuncND正確傳遞參數

這是傳遞參數myNum的電話:

id action2 = [CCCallFuncND actionWithTarget:self selector:@selector(playNote:data:) data:(NSNumber *)myNum]; 

這是整個街區:

- (void)muteAndPlayNote:(NSInteger)noteValue :(CCLayer*)currentLayer 
{ 
myNum = [NSNumber numberWithInteger:noteValue]; 

NSLog(@"Test the number: %d", [myNum integerValue]); 

id action1 = [CCCallFunc actionWithTarget:self selector:@selector(muteAudioInput)]; 

id action2 = [CCCallFuncND actionWithTarget:self selector:@selector(playNote:data:) data:(NSNumber *)myNum]; 

id action3 = [CCDelayTime actionWithDuration:3]; 

id action4 = [CCCallFunc actionWithTarget:self selector:@selector(unmuteAudioInput)]; 

[currentLayer runAction: [CCSequence actions:action1, action2, action3, action4, nil]]; 

} 

的NSLog永遠不會顯示任何崩潰在這條線。

- (void) playNote:(id)sender data:(NSNumber *)MIDInoteValue 

{ 
NSLog(@"Test number 2: %d", [MIDInoteValue integerValue]); 
int myInt = [MIDInoteValue floatValue]; 
[PdBase sendFloat: 55 toReceiver:@"midinote"]; 
[PdBase sendBangToReceiver:@"trigger"]; 
} 

回答

1

你的方法簽名是:

-(void)playNote:(id)sender data:(NSNumber*)MIDInoteValue 

,但它應該是:

-(void)playNote:(id)sender data:(void*)data 

這在CCActionInstant.h定義爲:

typedef void (*CC_CALLBACK_ND)(id, SEL, id, void *); 

而且我很確定你從中得到了一些信息崩潰,如調用堆棧結束控制檯輸出,將有助於將其粘貼到此處以防萬一我錯了;)

+0

這是罪魁禍首!它解決了。謝謝 – enamodeka

2

請注意,如果您使用ARC,則CCCallFunc *操作本質上是不安全的。

無論使用CCCallBlock *操作(在ARC下安全使用)通常都會更好,因爲那樣您通常不需要傳入數據作爲參數,只需使用本地作用域的變量在塊內部:

myNum = [NSNumber numberWithInteger:noteValue]; 
[CCCallBlock actionWithBlock:^{ 
    NSInteger myInt = [myNum integerValue]; 
    // do something with myInt, or just use noteValue directly 
}]; 

PS:檢查你的代碼的數據類型一致性。您創建NSNumber myNum作爲NSInteger值,稍後通過floatValue方法獲得它,該方法將該數字隱式轉換爲float,然後返回到int(改用integerValue)。你將它分配給一個int的值,它只在32位系統上與int相同,在像iPhone 5S這樣的64位系統上,NSInteger實際上是64位類型(使用NSInteger而不是int)。

如果您在使用完全相同的數據類型時不一致,則可能會出現令人討厭的值轉換問題(以及爲64位設備構建時出現的問題)。另外,你甚至可能已經對此發出警告 - 認真對待這些警告。

+0

感謝您指出了這一點,知道這將節省我頭痛的下線 – enamodeka

1

對於具有此功能的遇到問題,這裏的工作版本:

id action2 = [CCCallFuncND actionWithTarget:self selector:@selector(playNote:data:) data:(void *)noteValue]; 

,然後定義:

- (void) playNote:(id)sender data:(void *)midiNoteCode 

{ 
int myNum = midiNoteCode; //void * to int conversion may cause problems on 64bit platform, wrap it into NSInteger 
[PdBase sendFloat: (float)myNum toReceiver:@"midinote"]; 
[PdBase sendBangToReceiver:@"trigger"]; 

}