zoukankan      html  css  js  c++  java
  • ios 进阶技术点

    1.Runtime的消息转发机制

    消息转发机制基本上分为三个步骤: 
    1. 动态方法解析 
    2. 备用接收者 
    3. 完整转发

    2.Runloop的工作原理

    runloop、autorelease pool以及线程之间的关系。

    每个线程(包含主线程)都有一个Runloop。对于每一个Runloop,系统会隐式创建一个Autorelease pool,这样所有的release pool会构成一个像callstack一样的一个栈式结构,在每一个Runloop结束时,当前栈顶的Autorelease pool会被销毁,这样这个pool里的每个Object会被release。

    3.内存管理

    1.什么是ARC?

    ARC是automatic reference counting自动引用计数,在程序编译时自动加入retain/release。在对象被创建时retain count+1,在对象被release时count-1,当count=0时,销毁对象。程序中加入autoreleasepool对象会由系统自动加上autorelease方法,如果该对象引用计数为0,则销毁。那么ARC是为了解决MRC手动管理内存存在的一些而诞生的。

    MRC下内存管理的缺点:

    • 释放一个堆内存时,首先要确定指向这个堆空间的指针都被release了。(避免提前释放)

    • 释放指针指向的堆空间,首先要确定哪些指向同一个堆,这些指针只能释放一次。(避免释放多次,造成内存泄露)

    • 模块化操作时,对象可能被多个模块创建和使用,不能确定最后由谁释放

    • 多线程操作时,不确定哪个线程最后使用完毕。

    虽然ARC给我们编程带来的很多好多,但也可能出现内存泄露。如下面两种情况:

    • 循环参照:A有个属性参照B,B有个属性参照A,如果都是strong参照的话,两个对象都无法释放。

    • 死循环:如果有个ViewController中有无限循环,也会导致即使ViewController对应的view消失了,ViewController也不能释放。

    2.block一般用那个关键字修饰,为什么?

    block一般使用copy关键之进行修饰,block使用copy是从MRC遗留下来的“传统”,在MRC中,方法内容的block是在栈区的,使用copy可以把它放到堆区。但在ARC中写不写都行:编译器自动对block进行了copy操作。

    3.用@property声明的NSString(或NSArray,NSDictionary)经常使用copy关键字,为什么?如果改用strong关键字,可能造成什么问题?

    答:用@property声明 NSString、NSArray、NSDictionary 经常使用copy关键字,是因为他们有对应的可变类型:NSMutableString、NSMutableArray、NSMutableDictionary,他们之间可能进行赋值操作,为确保对象中的字符串值不会无意间变动,应该在设置新属性值时拷贝一份。

    如果我们使用是strong,那么这个属性就有可能指向一个可变对象,如果这个可变对象在外部被修改了,那么会影响该属性。

    copy此特质所表达的所属关系与strong类似。然而设置方法并不保留新值,而是将其“拷贝” (copy)。 当属性类型为NSString时,经常用此特质来保护其封装性,因为传递给设置方法的新值有可能指向一个NSMutableString类的实例。这个类是NSString的子类,表示一种可修改其值的字符串,此时若是不拷贝字符串,那么设置完属性之后,字符串的值就可能会在对象不知情的情况下遭人更改。所以,这时就要拷贝一份“不可变” (immutable)的字符串,确保对象中的字符串值不会无意间变动。只要实现属性所用的对象是“可变的” (mutable),就应该在设置新属性值时拷贝一份。

    4.runloop、autorelease pool以及线程之间的关系。

    每个线程(包含主线程)都有一个Runloop。对于每一个Runloop,系统会隐式创建一个Autorelease pool,这样所有的release pool会构成一个像callstack一样的一个栈式结构,在每一个Runloop结束时,当前栈顶的Autorelease pool会被销毁,这样这个pool里的每个Object会被release。

    5.@property 的本质是什么?ivar、getter、setter 是如何生成并添加到这个类中的。

    “属性”(property)有两大概念:ivar(实例变量)、存取方法(access method=getter),即@property = ivar + getter + setter。

    例如下面的这个类:

    1
    2
    3
    4
    @interface WBTextView :UITextView  
    @property (nonatomic,copy)NSString *placehold;  
    @property (nonatomic,copy)UIColor *placeholdColor;  
    @end

    类完成属性的定以后,编译器会自动编写访问这些属性的方法(自动合成autosynthesis),上述代码写出来的类等效与下面的代码:

    1
    2
    3
    4
    5
    6
    @interface WBTextView :UITextView  
    - (NSString *)placehold;  
    -(void)setPlacehold:(NSString *)placehold;  
    -(UIColor *)placeholdColor;  
    -(void)setPlaceholdColor:(UIColor *)placeholdColor;  
    @end

    详细介绍见:http://blog.csdn.net/jasonjwl/article/details/49427377

    6.分别写一个setter方法用于完成@property (nonatomic,retain)NSString *name和@property (nonatomic,copy) NSString *name

    retain属性的setter方法是保留新值并释放旧值,然后更新实例变量,令其指向新值。顺序很重要。假如还未保留新值就先把旧值释放了,而且两个值又指向同一个对象,先执行的release操作就可能导致系统将此对象永久回收。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    -(void)setName:(NSString *)name
    {
        [name retain];
        [_name release];
        _name = name;
    }
    -(void)setName:(NSString *)name
    {
         
        [_name release];
        _name = [name copy];
    }

    7.说说assign vs weak,_block vs _weak的区别

    assign适用于基本数据类型,weak是适用于NSObject对象,并且是一个弱引用。

    assign其实页可以用来修饰对象,那么为什么不用它呢?因为被assign修饰的对象在释放之后,指针的地址还是存在的,也就是说指针并没有被置为nil。如果在后续内存分配中,刚才分到了这块地址,程序就会崩溃掉。而weak修饰的对象在释放之后,指针地址会被置为nil。

    _block是用来修饰一个变量,这个变量就可以在block中被修改。

    _block:使用_block修饰的变量在block代码块中会被retain(ARC下,MRC下不会retain)

    _weak:使用_weak修饰的变量不会在block代码块中被retain

    8.请说出下面代码是否有问题,如果有问题请修改?

    1
    2
    3
    4
    5
    6
    @autoreleasepool {
            for (int i=0; i[largeNumber; i++) { (因识别问题,该行代码中尖括号改为方括号代替)
                Person *per = [[Person alloc] init];
                [per autorelease];
            }
        }

    内存管理的原则:如果对一个对象使用了alloc、copy、retain,那么你必须使用相应的release或者autorelease。咋一看,这道题目有alloc,也有autorelease,两者对应起来,应该没问题。但autorelease虽然会使引用计数减一,但是它并不是立即减一,它的本质功能只是把对象放到离他最近的自动释放池里。当自动释放池销毁了,才会向自动释放池中的每一个对象发送release消息。这道题的问题就在autorelease。因为largeNumber是一个很大的数,autorelease又不能使引用计数立即减一,所以在循环结束前会造成内存溢出的问题。

    解决方案如下:

    1
    2
    3
    4
    5
    6
    7
    8
    @autoreleasepool {
            for (int i=0; i[100000; i++) { (因识别问题,该行代码中尖括号改为方括号代替)
                @autoreleasepool {
                Person *per = [[Person alloc] init];
                [per autorelease];
            }
          }
        }

    在循环内部再加一个自动释放池,这样就能保证每创建一个对象就能及时释放。

    9.请问下面代码是否有问题,如有问题请修改?

    1
    2
    3
    4
    5
    6
    7
    8
    9
    @autoreleasepool {
            NSString *str = [[NSString alloc] init];
            [str retain];
            [str retain];
            str = @"jxl";
            [str release];
            [str release];
            [str release];
    }

    这道题跟第8题一样存在内存泄露问题,1.内存泄露 2.指向常量区的对象不能release。

    指针变量str原本指向一块开辟的堆区空间,但是经过重新给str赋值,str的指向发生了变化,由原来指向堆区空间,到指向常量区。常量区的变量根本不需要释放,这就导致了原来开辟的堆区空间没有释放,照成内存泄露。

    10.什么情况下使用weak关键字,相比assign有什么不同?什么情况使用weak关键字?

    • 在ARC中,在有可能出现循环引用的时候,往往要通过让其中一端使用weak来解决。比如delegate代理

    • 自身已经对它进行一次强引用,没有必要再强引用一次,此时也会使用weak,自定义控件属性一般也使用weak。

    不同点:

    • weak此特质表明该属性定义了一种“非拥有关系”。为这种属性设置新值时,设置方法既不保留新值,也不释放旧值。此特性与assign一样,然而在属性所指的对象遭到推毁时,属性值也会清空。而assign的“设置方法”只会执行针对“纯量类型” (scalar type,例如 CGFloat 或 NSlnteger 等)的简单赋值操作。

    • assign可以用非OC对象,而weak必须用于OC对象。

    11.内存管理语义(assign、strong、weak等的区别)

    • assign “设置方法” 只会执行针对“纯量”的简单赋值操作。

    • strong  此特质表明该属性定义了一种“拥有关系”。为这种属性设置新值时,设置方法会先保留新值,并释放旧值,然后再将新值设置上去。

    • weak 此特质表明该属性定义了一种“非拥有关系”。为这种属性设置新值时,设置方法既不保留新值,也不释放旧值。此特质同assign类似,然而在属性所指的对象遭到推毁时,属性值也会清空。

    • unsafe_unretained  此特质的语义和assign相同,但是它适用于“对象类型”,该特质表达一种“非拥有关系”,当目标对象遭到推毁时,属性值不会自动清空,这一点与weak有区别。

    • copy 此特质所表达的所属关系与strong类似。然而设置方法并不保留新值,而是设置方法并不保留新值,而是将其“拷贝”。当属性类型为NSString*时,经常用此特质来保护其封装性,因为传递给设置方法的新值有可能指向一个NSMutableString类的实例。这个类是NSString的子类,表示一种可以修改其值的字符串,此时若是不拷贝字符串,那么设置完属性之后,字符串的值就可能会在对象不知情的情况下遭人更改。所以,这时就要拷贝一份“不可变”的字符串,确保对象中的字符串值不会无意间变动。只要实现属性所用的对象是“可变的”,就应该在设置新属性值时拷贝一份。

    4.block

    5.GCD

    6.定时器的几个类方法底层分别是怎么实现的([NSTimer timerWithTimeInterval:repeats: block:]等)

    7.KVO、delegate、通知的区别以及底层实现

    8.Struct与Union主要区别

    9.点击应用图标到启动应用整个过程,系统进行了什么操作

    10.swift相关知识

    11.Apple pay的支付流程

    12.+的实现逻辑

    13.runtime的相关知识

    14.autorelease的使用场景

    15.plist读写操作如何进行锁管理

    16.NSNotification实现逻辑,子线程中给主线程发送通知,主线程是否会处理通知

    先来看看官方的文档,是这样写的:

    In a multithreaded application, notifications are always delivered in the thread in which the notification was posted, which may not be the same thread in which an observer registered itself.

    翻译过来是:

    在多线程应用中,Notification在哪个线程中post,就在哪个线程中被转发,而不一定是在注册观察者的那个线程中。

    也就是说,Notification的发送与接收处理都是在同一个线程中。为了说明这一点,我们先来看一个示例:

    代码清单1:Notification的发送与处理

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    @implementation ViewController
     
    - (void)viewDidLoad {
        [super viewDidLoad];
     
        NSLog(@"current thread = %@", [NSThread currentThread]);
     
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:TEST_NOTIFICATION object:nil];
     
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
     
            [[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil userInfo:nil];
        });
    }
     
    - (void)handleNotification:(NSNotification *)notification
    {
        NSLog(@"current thread = %@", [NSThread currentThread]);
     
        NSLog(@"test notification");
    }
     
    @end

    其输出结果如下:

    1
    2
    3
    2015-03-11 22:05:12.856 test[865:45102] current thread = {number = 1, name = main}
    2015-03-11 22:05:12.857 test[865:45174] current thread = {number = 2, name = (null)}
    2015-03-11 22:05:12.857 test[865:45174] test notification

    可以看到,虽然我们在主线程中注册了通知的观察者,但在全局队列中post的Notification,并不是在主线程处理的。所以,这时候就需要注意,如果我们想在回调中处理与UI相关的操作,需要确保是在主线程中执行回调。

    这时,就有一个问题了,如果我们的Notification是在二级线程中post的,如何能在主线程中对这个Notification进行处理呢?或者换个提法,如果我们希望一个Notification的post线程与转发线程不是同一个线程,应该怎么办呢?我们看看官方文档是怎么说的:

    For example, if an object running in a background thread is listening for notifications from the user interface, such as a window closing, you would like to receive the notifications in the background thread instead of the main thread. In these cases, you must capture the notifications as they are delivered on the default thread and redirect them to the appropriate thread.

    这里讲到了“重定向”,就是我们在Notification所在的默认线程中捕获这些分发的通知,然后将其重定向到指定的线程中。

    一种重定向的实现思路是自定义一个通知队列(注意,不是NSNotificationQueue对象,而是一个数组),让这个队列去维护那些我们需要重定向的Notification。我们仍然是像平常一样去注册一个通知的观察者,当Notification来了时,先看看post这个Notification的线程是不是我们所期望的线程,如果不是,则将这个Notification存储到我们的队列中,并发送一个信号(signal)到期望的线程中,来告诉这个线程需要处理一个Notification。指定的线程在收到信号后,将Notification从队列中移除,并进行处理。

    官方文档已经给出了示例代码,在此借用一下,以测试实际结果:

    代码清单2:在不同线程中post和转发一个Notification

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    @interface ViewController () @property (nonatomic) NSMutableArray    *notifications;         // 通知队列
    @property (nonatomic) NSThread          *notificationThread;    // 期望线程
    @property (nonatomic) NSLock            *notificationLock;      // 用于对通知队列加锁的锁对象,避免线程冲突
    @property (nonatomic) NSMachPort        *notificationPort;      // 用于向期望线程发送信号的通信端口
     
    @end
     
    @implementation ViewController
     
    - (void)viewDidLoad {
        [super viewDidLoad];
     
        NSLog(@"current thread = %@", [NSThread currentThread]);
     
        // 初始化
        self.notifications = [[NSMutableArray alloc] init];
        self.notificationLock = [[NSLock alloc] init];
     
        self.notificationThread = [NSThread currentThread];
        self.notificationPort = [[NSMachPort alloc] init];
        self.notificationPort.delegate = self;
     
        // 往当前线程的run loop添加端口源
        // 当Mach消息到达而接收线程的run loop没有运行时,则内核会保存这条消息,直到下一次进入run loop
        [[NSRunLoop currentRunLoop] addPort:self.notificationPort
                                    forMode:(__bridge NSString *)kCFRunLoopCommonModes];
     
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(processNotification:) name:@"TestNotification" object:nil];
     
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
     
            [[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil userInfo:nil];
     
        });
    }
     
    - (void)handleMachMessage:(void *)msg {
     
        [self.notificationLock lock];
     
        while ([self.notifications count]) {
            NSNotification *notification = [self.notifications objectAtIndex:0];
            [self.notifications removeObjectAtIndex:0];
            [self.notificationLock unlock];
            [self processNotification:notification];
            [self.notificationLock lock];
        };
     
        [self.notificationLock unlock];
    }
     
    - (void)processNotification:(NSNotification *)notification {
     
        if ([NSThread currentThread] != _notificationThread) {
            // Forward the notification to the correct thread.
            [self.notificationLock lock];
            [self.notifications addObject:notification];
            [self.notificationLock unlock];
            [self.notificationPort sendBeforeDate:[NSDate date]
                                       components:nil
                                             from:nil
                                         reserved:0];
        }
        else {
            // Process the notification here;
            NSLog(@"current thread = %@", [NSThread currentThread]);
            NSLog(@"process notification");
        }
    }
     
    @end

    运行后,其输出如下:

    1
    2
    3
    2015-03-11 23:38:31.637 test[1474:92483] current thread = {number = 1, name = main}
    2015-03-11 23:38:31.663 test[1474:92483] current thread = {number = 1, name = main}
    2015-03-11 23:38:31.663 test[1474:92483] process notification

    可以看到,我们在全局dispatch队列中抛出的Notification,如愿地在主线程中接收到了。

    这种实现方式的具体解析及其局限性大家可以参考官方文档Delivering Notifications To Particular Threads,在此不多做解释。当然,更好的方法可能是我们自己去子类化一个NSNotificationCenter,或者单独写一个类来处理这种转发。

    NSNotificationCenter的线程安全性

    苹果之所以采取通知中心在同一个线程中post和转发同一消息这一策略,应该是出于线程安全的角度来考量的。官方文档告诉我们,NSNotificationCenter是一个线程安全类,我们可以在多线程环境下使用同一个NSNotificationCenter对象而不需要加锁。原文在Threading Programming Guide中,具体如下:

    1
    2
    3
    4
    5
    6
    7
    The following classes and functions are generally considered to be thread-safe. You can use the same instance from multiple threads without first acquiring a lock.
     
    NSArray
    ...
    NSNotification
    NSNotificationCenter
    ...

    我们可以在任何线程中添加/删除通知的观察者,也可以在任何线程中post一个通知。

    NSNotificationCenter在线程安全性方面已经做了不少工作了,那是否意味着我们可以高枕无忧了呢?再回过头来看看第一个例子,我们稍微改造一下,一点一点来:

    代码清单3:NSNotificationCenter的通用模式

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    @interface Observer : NSObject
     
    @end
     
    @implementation Observer
     
    - (instancetype)init
    {
        self = [super init];
     
        if (self)
        {
            _poster = [[Poster alloc] init];
     
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:TEST_NOTIFICATION object:nil]
        }
     
        return self;
    }
     
    - (void)handleNotification:(NSNotification *)notification
    {
        NSLog(@"handle notification ");
    }
     
    - (void)dealloc
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
     
    @end
     
    // 其它地方
    [[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil];

    上面的代码就是我们通常所做的事情:添加一个通知监听者,定义一个回调,并在所属对象释放时移除监听者;然后在程序的某个地方post一个通知。简单明了,如果这一切都是发生在一个线程里面,或者至少dealloc方法是在-postNotificationName:的线程中运行的(注意:NSNotification的post和转发是同步的),那么都OK,没有线程安全问题。但如果dealloc方法和-postNotificationName:方法不在同一个线程中运行时,会出现什么问题呢?

    我们再改造一下上面的代码:

    代码清单4:NSNotificationCenter引发的线程安全问题

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    #pragma mark - Poster
     
    @interface Poster : NSObject
     
    @end
     
    @implementation Poster
     
    - (instancetype)init
    {
        self = [super init];
     
        if (self)
        {
            [self performSelectorInBackground:@selector(postNotification) withObject:nil];
        }
     
        return self;
    }
     
    - (void)postNotification
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil];
    }
     
    @end
     
    #pragma mark - Observer
     
    @interface Observer : NSObject
    {
        Poster  *_poster;
    }
     
    @property (nonatomic, assign) NSInteger i;
     
    @end
     
    @implementation Observer
     
    - (instancetype)init
    {
        self = [super init];
     
        if (self)
        {
            _poster = [[Poster alloc] init];
     
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:TEST_NOTIFICATION object:nil];
        }
     
        return self;
    }
     
    - (void)handleNotification:(NSNotification *)notification
    {
        NSLog(@"handle notification begin");
        sleep(1);
        NSLog(@"handle notification end");
     
        self.i = 10;
    }
     
    - (void)dealloc
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
     
        NSLog(@"Observer dealloc");
    }
     
    @end
     
    #pragma mark - ViewController
     
    @implementation ViewController
     
    - (void)viewDidLoad {
        [super viewDidLoad];
     
        __autoreleasing Observer *observer = [[Observer alloc] init];
    }
     
    @end

    这段代码是在主线程添加了一个TEST_NOTIFICATION通知的监听者,并在主线程中将其移除,而我们的NSNotification是在后台线程中post的。在通知处理函数中,我们让回调所在的线程睡眠1秒钟,然后再去设置属性i值。这时会发生什么呢?我们先来看看输出结果:

    1
    2
    3
    4
    5
    6
    2015-03-14 00:31:41.286 SKTest[932:88791] handle notification begin
    2015-03-14 00:31:41.291 SKTest[932:88713] Observer dealloc
    2015-03-14 00:31:42.361 SKTest[932:88791] handle notification end
    (lldb) 
     
    // 程序在self.i = 10处抛出了"Thread 6: EXC_BAD_ACCESS(code=EXC_I386_GPFLT)"

    经典的内存错误,程序崩溃了。其实从输出结果中,我们就可以看到到底是发生了什么事。我们简要描述一下:

    1. 当我们注册一个观察者是,通知中心会持有观察者的一个弱引用,来确保观察者是可用的。

    2. 主线程调用dealloc操作会让Observer对象的引用计数减为0,这时对象会被释放掉。

    3. 后台线程发送一个通知,如果此时Observer还未被释放,则会用其转出消息,并执行回调方法。而如果在回调执行的过程中对象被释放了,就会出现上面的问题。

    当然,上面这个例子是故意而为之,但不排除在实际编码中会遇到类似的问题。虽然NSNotificationCenter是线程安全的,但并不意味着我们在使用时就可以保证线程安全的,如果稍不注意,还是会出现线程问题。

    那我们该怎么做呢?这里有一些好的建议:

    1. 尽量在一个线程中处理通知相关的操作,大部分情况下,这样做都能确保通知的正常工作。不过,我们无法确定到底会在哪个线程中调用dealloc方法,所以这一点还是比较困难。

    2. 注册监听都时,使用基于block的API。这样我们在block还要继续调用self的属性或方法,就可以通过weak-strong的方式来处理。具体大家可以改造下上面的代码试试是什么效果。

    3. 使用带有安全生命周期的对象,这一点对象单例对象来说再合适不过了,在应用的整个生命周期都不会被释放。

    4. 使用代理。

    小结

    NSNotificationCenter虽然是线程安全的,但不要被这个事实所误导。在涉及到多线程时,我们还是需要多加小心,避免出现上面的线程问题

    17.编译器怎么检测#import和#include导入多次的问题,三方库导入时如何设置**""和<>**

    18.写一段程序判断文本框内输入的IP地址是否合法

    19.两种单例模式

    单例模式实现方式是在类中编写名为sharedInstance的方法,该方法只会返回全类共用的单例实例,而不会在每次调用时都创建新的实例。

     使用同步块实现:

    + (id)sharedInstance {
    
        static ClassName *sharedInstance = nil;
    
        @synchronized (self) {
    
            if (!sharedInstance) {
    
                sharedInstance = [[self alloc]init];
    
            }
    
        }
    
        return sharedInstance;
    
    }

    GCD引入了一个新特征,更为方便:

    + (instancetype)sharedInstance {
    
        static ClassName *sharedInstance = nil;
    
        static dispatch_once_t onceToken;
    
        dispatch_once(&onceToken, ^{
    
            sharedInstance = [[self alloc]init];
    
        });
    
        return sharedInstance;
    
    }

    使用dispatch_once的注意事项:

        此函数接收类型为dispatch_once_t的特殊参数,还有一个块参数。对于onceToken标记,该函数保证相关的块必定会执行,且执行一次。此操作完全是线程安全的。注意:对于只执行一次的块来说,对于传入函数的标记参数必须完全相同,因此,开发时需要将标记变量声明在static或global作用于中。

    对于在dispatch_once中的创建的实例对象必须确保其只有一个,所以使用static修饰

        上述两种实现单例的方法比较:使用dispatch_once可以简化代码且保证线程安全,开发者无需担心加锁或同步。所有问题都在GCD底层处理。此外,dispatch_once更高效。它没有使用重量级的同步机制。使用同步机制,每次运行代码都需要获取锁。dispatch_once采用“原子访问”来查询标记,判断代码是否执行过。

    最后附图一张在线课程学习的目录

  • 相关阅读:
    EntityFramework.Extended 支持 MySql
    向着那个理想的世界奔跑
    DDD 领域驱动设计-两个实体的碰撞火花
    云自无心水自闲
    JQuery 复制粘贴上传图片插件(textarea 和 tinyMCE)
    理解 .NET Platform Standard
    【补充】Gitlab 部署 CI 持续集成
    DDD 领域驱动设计-领域模型中的用户设计
    CSS float 定位和缩放问题
    JQuery 加载 CSS、JS 文件
  • 原文地址:https://www.cnblogs.com/weiboyuan/p/9000906.html
Copyright © 2011-2022 走看看