iOS 多线程安全 与可变数组

Posted ACM_Someone like you

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS 多线程安全 与可变数组相关的知识,希望对你有一定的参考价值。

完全来自于 iOS 多线程安全与可变字典 的学习

基本相同,举一反三

直接上样例代码

是我参照网上,根据当前业务需求改的。

其实好多人在这里喜欢用类别处理。我个人觉得用类别 极其容易和普通方法混淆,所以为了降低耦合度,增强代码理解性和可读性。这里单独创建类挺好的。用时候使用这个自定义的安全数组就好了。

//  MensesTracker
//
//  Created by HF on 2018/6/7.
//  Copyright © 2018年 huofar. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface SyncMutableArray : NSObject

//只读
- (NSMutableArray *)safeArray;

//判断是否包含对象
- (BOOL)containsObject:(id)anObject;

//集合元素数量
- (NSUInteger)count;

//获取元素
- (id)objectAtIndex:(NSUInteger)index;
//枚举元素
- (NSEnumerator *)objectEnumerator;
//插入
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;
//插入
- (void)addObject:(id)anObject;
//移除
- (void)removeObjectAtIndex:(NSUInteger)index;
//移除
- (void)removeObject:(id)anObject;
//移除
- (void)removeLastObject;
//替换
- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
//获取索引
- (NSUInteger)indexOfObject:(id)anObject;

@end
//
//  SyncMutableArray.m
//  MensesTracker
//
//  Created by HF on 2018/6/7.
//  Copyright © 2018年 huofar. All rights reserved.
//

#import "SyncMutableArray.h"

@interface SyncMutableArray ()

@property (nonatomic, strong) dispatch_queue_t syncQueue;
@property (nonatomic, strong) NSMutableArray* array;

@end

@implementation SyncMutableArray

#pragma mark - init 方法
- (instancetype)initCommon
{
    self = [super init];
    if (self) {
        //%p 以16进制的形式输出内存地址,附加前缀0x
        NSString* uuid = [NSString stringWithFormat:@"com.huofar.array_%p", self];
        //注意:_syncQueue是并行队列
        _syncQueue = dispatch_queue_create([uuid UTF8String], DISPATCH_QUEUE_CONCURRENT);
    }
    return self;
}

- (instancetype)init
{
    self = [self initCommon];
    if (self) {
        _array = [NSMutableArray array];
    }
    return self;
}

//其他init方法略

#pragma mark - 数据操作方法 (凡涉及更改数组中元素的操作,使用异步派发+栅栏块;读取数据使用 同步派发+并行队列)

- (NSMutableArray *)safeArray
{
    __block NSMutableArray *safeArray;
    dispatch_sync(_syncQueue, ^{
        safeArray = _array;
    });
    return safeArray;
}

- (BOOL)containsObject:(id)anObject
{
    __block BOOL isExist = NO;
    dispatch_sync(_syncQueue, ^{
        isExist = [_array containsObject:anObject];
    });
    return isExist;
}

- (NSUInteger)count
{
    __block NSUInteger count;
    dispatch_sync(_syncQueue, ^{
        count = _array.count;
    });
    return count;
}

- (id)objectAtIndex:(NSUInteger)index
{
    __block id obj;
    dispatch_sync(_syncQueue, ^{
        if (index < [_array count]) {
            obj = _array[index];
        }
    });
    return obj;
}

- (NSEnumerator *)objectEnumerator
{
    __block NSEnumerator *enu;
    dispatch_sync(_syncQueue, ^{
        enu = [_array objectEnumerator];
    });
    return enu;
}

- (void)insertObject:(id)anObject atIndex:(NSUInteger)index
{
    dispatch_barrier_async(_syncQueue, ^{
        if (anObject && index < [_array count]) {
            [_array insertObject:anObject atIndex:index];
        }
    });
}

- (void)addObject:(id)anObject
{
    dispatch_barrier_async(_syncQueue, ^{
        if(anObject){
            [_array addObject:anObject];
        }
    });
}

- (void)removeObjectAtIndex:(NSUInteger)index
{
    dispatch_barrier_async(_syncQueue, ^{
        
        if (index < [_array count]) {
            [_array removeObjectAtIndex:index];
        }
    });
}

- (void)removeObject:(id)anObject
{
    dispatch_barrier_async(_syncQueue, ^{
        [_array removeObject:anObject];//外边自己判断合法性
    });
}

- (void)removeLastObject
{
    dispatch_barrier_async(_syncQueue, ^{
        [_array removeLastObject];
    });
}

- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject
{
    dispatch_barrier_async(_syncQueue, ^{
        if (anObject && index < [_array count]) {
            [_array replaceObjectAtIndex:index withObject:anObject];
        }
    });
}

- (NSUInteger)indexOfObject:(id)anObject
{
    __block NSUInteger index = NSNotFound;
    dispatch_sync(_syncQueue, ^{
        for (int i = 0; i < [_array count]; i ++) {
            if ([_array objectAtIndex:i] == anObject) {
                index = i;
                break;
            }
        }
    });
    return index;
}

- (void)dealloc
{
    if (_syncQueue) {
        _syncQueue = NULL;
    }
}

@end

 

参考

1. https://www.aliyun.com/jiaocheng/354967.html

2.https://blog.csdn.net/zhang522802884/article/details/76728902

以上是关于iOS 多线程安全 与可变数组的主要内容,如果未能解决你的问题,请参考以下文章

StringBuilder线程为什么不安全

Java多线程——不变性与安全发布

Java的线程安全

线程安全

StringBuilder StringBuffer String辨析

线程安全