2012-03-07 67 views
0

我認爲將動畫數組傳遞給一個內部函數會一個接一個地運行所有動畫是一個絕妙的想法,所以我不需要在彼此之間嵌套動畫,彼此的完成塊。所以我寫了一個小方法來測試這個,猜猜它是什麼,它會像地獄一樣崩潰。但我不明白爲什麼。這是我的方法:當傳遞動畫數組時,應用程序崩潰

+(void) internalAnimateWithArrayOfAnimationBlocks:(NSArray*) animationBlocks withIndex:(NSUInteger) index withCompletionAnimation:(void (^)(BOOL finished)) completionBlock { 
    __block NSArray* newAnims = animationBlocks; 
    __block NSUInteger theIndex = index; 
    if (index < [newAnims count] - 1) { 
    [UIView animateWithDuration:0.1 animations:^{ 
     void (^animBlock) (void) = [newAnims objectAtIndex:theIndex]; 
     animBlock(); 
     theIndex++; 
     [RMAnimater internalAnimateWithArrayOfAnimationBlocks:newAnims withIndex:theIndex withCompletionAnimation:completionBlock]; 
    }]; 
    } 
    else { 
    [UIView animateWithDuration:0.1 animations:^{ 
     void (^animBlock) (void) = [newAnims objectAtIndex:theIndex]; 
     animBlock(); 
     theIndex++; 
    } completion:completionBlock]; 
    } 
} 

+(void) animateWithArrayOfAnimationBlocks:(NSArray*) animationBlocks withCompletionAnimation:(void (^)(BOOL finished)) completionBlock { 
    [RMAnimater internalAnimateWithArrayOfAnimationBlocks:animationBlocks withIndex:0 withCompletionAnimation:completionBlock]; 
} 

我通過這個動畫是這樣的:

NSMutableArray* animations = [NSMutableArray array]; 
[animations addObject:^{ 
    CGRect frame = theTile.textField.frame; 
    frame.origin.x -= 10; 
    theTile.textField.frame = frame; 
}]; 

當我調試它,它親切地通過我的所有動畫去,用其完成塊調用最終的動畫,然後崩潰致命。我在這裏做錯了什麼?

+1

「崩潰致命」不是很具體。怎麼了? – Jim 2012-03-07 13:21:09

回答

1

問題是,調用-addObject:NSMutableArray將保留但不復制添加的對象。當你聲明一個塊時,它會在堆棧中,這將在範圍的末尾被銷燬。要成堆,您必須Block_copy或發送copy消息到塊。所以要解決您的問題,您必須:

NSMutableArray* animations = [NSMutableArray array]; 
void (^animBlock)(void) = Block_copy(^{ 
    CGRect frame = theTile.textField.frame; 
    frame.origin.x -= 10; 
    theTile.textField.frame = frame; 
}); 
[animations addObject:animBlock]; 
Block_release(animBlock); 
+0

我以爲是這樣的..非常感謝! – Fuggly 2012-03-07 14:00:23

相關問題