[英]NSMutable Array High CPU Usage
我最近將c數組更改為NSMutable數組,因為我在內存方面遇到很多麻煩。 但是它有效,但是從
/* If two starttimes are within interval millisec, make them the same */
for (int i = 0; i < [starttimes count] - 1; i++) {
if ([[starttimes objectAtIndex:i+1] integerValue] - [[starttimes objectAtIndex:i] integerValue] <= interval) {
[starttimes insertObject: [starttimes objectAtIndex:i] atIndex:(i+1)];
}
}
CPU使用率接近100%。 不知發生了什么? 邏輯很簡單。 它所做的就是從此NSMutable數組中獲取兩個元素,然后進行比較和插入。 順便說一句,這段代碼永遠不會停止。 它持續運行3秒鍾,然后我的應用程序崩潰了。
(TimeSignature*)time {
/* Get all the starttimes in all tracks, in sorted order */
NSInteger initsize = 1;
if ([tracks count] > 0) {
MidiTrack *track = [tracks objectAtIndex:0];
initsize = [track.notes count];
initsize = initsize * [tracks count]/2;
}
NSMutableArray* starttimes = [[NSMutableArray alloc]initWithCapacity:initsize];
for (int tracknum = 0; tracknum < [tracks count]; tracknum++) {
NSLog(@"tracknum is %d",tracknum);
MidiTrack *track = [tracks objectAtIndex:tracknum];
NSLog(@"WE ARE HERE %ld",(long)initsize);
for (int j = 0; j < [track.notes count]; j++) {
MidiNote *note = [track.notes objectAtIndex:j];
NSLog(@"%@",note);
[starttimes addObject:[NSNumber numberWithInteger:note.startTime]];
}
}
/* Notes within "millisec" milliseconds apart should be combined */
int interval = time.quarter * millisec * 1000 / time.tempo;
/* If two starttimes are within interval millisec, make them the same */
for (int i = 0; i < [starttimes count] - 1; i++) {
if ([[starttimes objectAtIndex:i+1] integerValue] - [[starttimes objectAtIndex:i] integerValue] <= interval) {
[starttimes insertObject: [starttimes objectAtIndex:i] atIndex:(i+1)];
}
}
非常感謝
通用的Objective-C建議:閱讀方法名稱。 他們告訴您想要方法。
您誤解了-insertObject:
insertObject
作用是... 插入對象。 它不起作用:替換對象。 每次調用insertObject
時,都會增加數組的大小。 在實踐中, if
條件一次甚至通過, if
您將創建一個無限循環。
您可能需要-replaceObjectAtIndex:withObject:
就像insertObject:
,它將按照名稱中的說明進行操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.