typedef int (^IntBlock)(int, int);
IntBlock add = ^(int x, int y) { return x + y; };
NSLog(@"%d", add(1, 2)); // 3
__block 修飾:引用捕獲,可修改,且變數移至堆區共享。__block int x = 10;
void (^blk)(int) = ^(int n) { x++; NSLog(@"%d", x); };
blk(5); // x 變為 11
sortUsingComparator:[cars sortUsingComparator:^NSComparisonResult(Car *a, Car *b) {
if (a.price < b.price) return NSOrderedDescending; // 價格高到低
if (a.price == b.price) return NSOrderedSame;
return NSOrderedAscending;
}];
sortedArrayUsingComparator:NSArray *sorted = [cars sortedArrayUsingComparator:^NSComparisonResult(Car *a, Car *b) {
return [a.maxSpeed compare:b.maxSpeed]; // 利用 NSNumber 比較
}];
NSComparisonResult (^bySpeed)(Car*, Car*) = ^(Car *a, Car *b) { ... };
[cars sortUsingComparator:bySpeed];
| 類型 | 舊語法 | 字面量 |
|---|---|---|
| 字串 | [[NSString alloc] initWithUTF8String:"s"] | @"s" |
| 陣列 | [NSArray arrayWithObjects:@"a", @"b", nil] | @[@"a", @"b"] |
| 字典 | [NSDictionary dictionaryWithObjectsAndKeys:@"v", @"k", nil] | @{@"k": @"v"} |
| 數值 | [NSNumber numberWithInt:123] | @123 |
字典取值:dict[@"key"] 替代 [dict objectForKey:@"key"]。
__weak typeof(self) weakSelf = self; 在 Block 內使用。__block 變數在 Block 複製到堆時會一起移動,保證多個 Block 共享同一變數。