MST

星途 面试题库

面试题:Objective-C 中 Block 的基本使用场景有哪些

请列举至少三个 Objective-C 中 Block 的常见使用场景,并简要说明如何在这些场景中使用 Block。例如在 GCD 中的应用。
30.9万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试
  1. GCD(Grand Central Dispatch)中的应用
    • 说明:在GCD中,使用dispatch_asyncdispatch_sync等函数时,Block用于定义在队列中执行的任务。
    • 示例代码
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
    // 这里是在后台队列执行的代码
    NSLog(@"This is a background task.");
});
  1. 作为方法参数
    • 说明:许多系统框架的方法接受Block作为参数,用于在特定事件发生时执行自定义代码。比如UIView的动画方法animateWithDuration:animations:completion:
    • 示例代码
[UIView animateWithDuration:0.3 animations:^{
    // 动画相关的视图改变代码
    self.view.alpha = 0.5;
} completion:^(BOOL finished) {
    if (finished) {
        NSLog(@"Animation completed.");
    }
}];
  1. 集合遍历
    • 说明NSArrayNSDictionary等集合类有一些方法可以接受Block作为参数来对集合中的元素进行操作。例如NSArrayenumerateObjectsUsingBlock:方法。
    • 示例代码
NSArray *array = @[@"one", @"two", @"three"];
[array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    NSLog(@"Object at index %lu is %@", (unsigned long)idx, obj);
    if ([obj isEqualToString:@"two"]) {
        *stop = YES; // 停止遍历
    }
}];
  1. 网络请求回调
    • 说明:在进行网络请求时,使用Block来处理请求完成后的响应数据。以AFNetworking框架为例。
    • 示例代码
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:@"https://example.com/api" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    NSLog(@"Request success: %@", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSLog(@"Request failed: %@", error);
}];