首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Objective-C Block 深度解析:語法、捕獲機制與實戰場景

     編輯:關於C語言

Block 基礎語法

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 修飾符:允許在 Block 內修改外部變量,並將修改反映到外部作用域。
__block int counter = 0;
void (^increment)(void) = ^{
    counter++;
    NSLog(@"%d", counter);
};
increment(); // 1
increment(); // 2
// 外部 counter 也變為 2

實戰場景大全

1. 通知中心觀察者(替代目標-動作模式)

[[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillShowNotification
                                                    object:nil
                                                     queue:[NSOperationQueue mainQueue]
                                                usingBlock:^(NSNotification *notif) {
    // 處理鍵盤彈出邏輯
    CGRect kbFrame = [notif.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    // ...
}];

2. 視圖動畫與完成回調

[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;
    }
}];

3. 異步任務完成回調

NSOperationQueue *opQ = [[NSOperationQueue alloc] init];
[[NSNotificationCenter defaultCenter] addObserverForName:@"CustomOperationCompleted"
                                                    object:nil
                                                     queue:opQ
                                                usingBlock:^(NSNotification *notif) {
    NSNumber *num = notif.userInfo[@"NumberOfItemsProcessed"];
    NSLog(@"Processed: %@", num);
}];

4. 集合遍歷與過濾

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];

5. 字符串枚舉處理

[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);
    }
}];

6. 視圖轉場動畫

[UIView transitionWithView:containerView
                  duration:0.2
                   options:UIViewAnimationOptionTransitionFlipFromLeft
                animations:^{
    [fromView removeFromSuperview];
    [containerView addSubview:toView];
} completion:NULL];

7. 數組自定義排序

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];

內存管理要點

  1. Block 默認在棧上,逃逸時需 copy 到堆(ARC 環境下自動處理)。
  2. 避免循環引用:Block 內引用 self 時使用 __weak typeof(self) weakSelf = self;。
  3. __block 變量在 Block copy 時會一起複製到堆,多個 Block 可共享同一 __block 變量。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved