Block 是 iOS 4.0+ / macOS 10.6+ 引入的 C 語言擴展,實現匿名函數/閉包特性。語法核心:
返回類型 (^名稱)(參數列表) = ^(參數列表) { 函數體 };
示例:
int (^Multiply)(int, int) = ^(int num1, int num2) {
return num1 * num2;
};
int result = Multiply(7, 4); // 28
注意:聲明時 ^ 綁定名稱而非返回類型,這與函數指針不同。
__block int counter = 0;
void (^increment)(void) = ^{
counter++;
NSLog(@"%d", counter);
};
increment(); // 1
increment(); // 2
// 外部 counter 也變為 2
[[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillShowNotification
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *notif) {
// 處理鍵盤彈出邏輯
CGRect kbFrame = [notif.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
// ...
}];
[UIView animateWithDuration:1.5 animations:^{
self.imageView.frame = newFrame;
self.imageView.alpha = 0.2;
} completion:^(BOOL finished) {
if (finished) {
self.imageView.frame = originalFrame;
self.imageView.alpha = 1.0;
}
}];
NSOperationQueue *opQ = [[NSOperationQueue alloc] init];
[[NSNotificationCenter defaultCenter] addObserverForName:@"CustomOperationCompleted"
object:nil
queue:opQ
usingBlock:^(NSNotification *notif) {
NSNumber *num = notif.userInfo[@"NumberOfItemsProcessed"];
NSLog(@"Processed: %@", num);
}];
NSArray *timeZones = [NSTimeZone knownTimeZoneNames];
NSIndexSet *indexes = [timeZones indexesOfObjectsWithOptions:NSEnumerationConcurrent
passingTest:^BOOL(NSString *obj, NSUInteger idx, BOOL *stop) {
return [obj hasPrefix:@"Europe"];
}];
NSArray *europeZones = [timeZones objectsAtIndexes:indexes];
[musicDates enumerateSubstringsInRange:NSMakeRange(0, musicDates.length)
options:NSStringEnumerationByLines
usingBlock:^(NSString *substring, NSRange subRange, NSRange encRange, BOOL *stop) {
if ([substring rangeOfString:@"Beatles"].location != NSNotFound) {
NSLog(@"%@", substring);
}
}];
[UIView transitionWithView:containerView
duration:0.2
options:UIViewAnimationOptionTransitionFlipFromLeft
animations:^{
[fromView removeFromSuperview];
[containerView addSubview:toView];
} completion:NULL];
NSArray *strings = @[@"string 1", @"String 21", @"string 12", @"String 11", @"String 02"];
NSComparator comparator = ^NSComparisonResult(id s1, id s2) {
return [s1 compare:s2 options:NSCaseInsensitiveSearch | NSNumericSearch
range:NSMakeRange(0, [s1 length]) locale:[NSLocale currentLocale]];
};
NSArray *sorted = [strings sortedArrayUsingComparator:comparator];
copy 到堆(ARC 環境下自動處理)。self 時使用 __weak typeof(self) weakSelf = self;。__block 變量在 Block copy 時會一起複製到堆,多個 Block 可共享同一 __block 變量。