iOS 开发每天分享优质文章iOS-内存管理iOS开发实践

2019 iOS 面试 -中级篇之 Block

2019-08-21  本文已影响0人  赫子丰

1. block的实质是什么?一共有几种block?都是什么情况下生成的?

block的实质是什么?

查看block源码:

block定义:

struct Block_descriptor {
    unsigned long int reserved;
    unsigned long int size;
    void (*copy)(void *dst, void *src);
    void (*dispose)(void *);
};
 
struct Block_layout {
    void *isa;
    int flags;
    int reserved; 
    void (*invoke)(void *, ...);
    struct Block_descriptor *descriptor;
    /* Imported variables. */

一共有几种block?

都是什么情况下生成的?

2. 为什么在默认情况下无法修改被block捕获的变量? __block都做了什么?

Block只捕获Block中会用到的变量。由于只捕获了自动变量(自动变量是以值传递方式传递到Block的构造函数里面)的值,并非内存地址,所以Block内部不能改变自动变量的值。Block捕获的外部变量可以改变值的是静态变量,静态全局变量,全局变量。

参考:深入研究Block捕获外部变量和__block实现原理

如何在block中修改外部自动变量的值,主要有以下2种方法:

3. 模拟一下循环引用的一个情况?block实现界面反向传值如何实现?

循环引用:

#import <Foundation/Foundation.h>
typedef void(^Study)();  
@interface Student : NSObject
@property (copy , nonatomic) NSString *name;
@property (copy , nonatomic) Study study;
@end


#import "ViewController.h"
#import "Student.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
  
    Student *student = [[Student alloc]init];
    student.name = @"Hello World";
 
    student.study = ^{
        NSLog(@"my name is = %@",student.name);
    };

block界面反向传值实例:
1、在第二个视图控制器的.h文件中定义声明Block属性:

// NextViewController.h
// 定义block
@property (nonatomic,copy) void (^NextViewControllerBlock)
(NSString *tfText);
// NextViewController.m
@interface NextViewController ()
@property (weak, nonatomic) IBOutlet UITextField *inputTF;
@end
 
- (IBAction)BtnAction:(id)sender {
    //判断block是否为空
    if (self.NextViewControllerBlock) {
        self.NextViewControllerBlock(self.inputTF.text);   
    }
    [self.navigationController popViewControllerAnimated:YES];
}

2、在第一个视图中获得第二个视图控制器,并且用第二个视图控制器来调用定义的属性:

// AViewController.m
@interface AViewController ()
@property (weak, nonatomic) IBOutlet UILabel *nextVCInfoLabel;
@end
 
- (IBAction)btnClicked:(id)sender {
    NextViewController *nextVC = [[NextViewController alloc]init];
    nextVC.NextViewControllerBlock = ^(NSString *tfText){
        self.nextVCInfoLabel.text = tfText;
    };
    [self.navigationController pushViewController:nextVC animated:YES];
}

4. NSTImer的循环引用问题

使用NSTimer可能会碰到循环引用的问题。特别是当类具有NSTimer类型的成员变量,并且需要反复执行计时任务时。例如

_timer = [NSTimer scheduledTimerWithTimeInterval:5.0
                                          target:self
                                        selector:@selector(startCounting)   userInfo:nil
                                         repeats:YES];

类有一个成员变量_timer,给_timer设置的target为这个类本身。这样类保留_timer,_timer又保留了这个类,就会出现循环引用的问题,最后导致类无法正确释放。

解决这个问题的方式也很简单,当类的使用者能够确定不需要使用这个计时器时,就调用

[_timer invalidate];
_timer = nil;

这样就打破了保留环,类也可以正确释放。但是,这种依赖于开发者手动调用方法,才能让内存正确释放的方式不是一个非常好的处理方式。所以需要另外一种解决方案。
如下所示:

@interface NSTimer (JQUsingBlock)
+ (NSTimer *)jq_scheduledTimerWithTimeInterval:(NSTimeInterval)ti
                                     block:(void(^)())block
                                   repeats:(BOOL)repeats;
@end
 
@implementation NSTimer (JQUsingBlock)
 
+ (NSTimer *)jq_scheduledTimerWithTimeInterval:(NSTimeInterval)ti
                                     block:(void(^)())block
                                   repeats:(BOOL)repeats{
    return [self scheduledTimerWithTimeInterval:ti
                                     target:self                                                                        selector:@selector(jq_blockInvoke:)
                                   userInfo:[block copy]
                                    repeats:repeats];
}
 
+ (void)jq_blockInvoke:(NSTimer *)timer{
    void(^block)() = timer.userInfo;
    if (block) {
        block();
    }
}
 
@end

定义一个NSTimer的类别,在类别中定义一个类方法。类方法有一个类型为块的参数(定义的块位于栈上,为了防止块被释放,需要调用copy方法,将块移到堆上)。
使用这个类别的方式如下:

__weak ViewController *weakSelf = self;
_timer = [NSTimer jq_scheduledTimerWithTimeInterval:5.0
                        block:^{
                                __strong ViewController *strongSelf = weakSelf;
                                [strongSelf startCounting];
                                }
                      repeats:YES];

使用这种方案就可以防止NSTimer对类的保留,从而打破了循环引用的产生。__strong ViewController *strongSelf = weakSelf主要是为了防止执行块的代码时,类被释放了。在类的dealloc方法中,记得调用[_timer invalidate]。

相关阅读:

1、iOS 面试题 --- 基础部分
2、iOS 面试题 --- 中级篇 Runtime
3、iOS 面试题 --- 中级篇 Runloop
4、iOS 面试题 --- 高级篇

上一篇下一篇

猜你喜欢

热点阅读