直接拿走:
//
// LWThreadSafeArray.h
// P2PCamera
//
// Created by vigas on 2024/10/11.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface LWThreadSafeArray<ObjectType> : NSMutableArray<ObjectType>
- (void)addObject:(id)anObject;
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;
- (void)removeLastObject;
- (void)removeObjectAtIndex:(NSUInteger)index;
- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
@end
NS_ASSUME_NONNULL_END
//
// LWThreadSafeArray.m
// P2PCamera
//
// Created by vigas on 2024/10/11.
//
#import "LWThreadSafeArray.h"
@interface LWThreadSafeArray()
{
NSMutableArray *_arr;
}
@property (nonatomic, strong) dispatch_queue_t syncQueue;
@end
@implementation LWThreadSafeArray
- (instancetype)init {
self = [super init];
if (self) {
_arr = [NSMutableArray array];
[self syncQueue];
}
return self;
}
- (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)idx {
dispatch_barrier_async(self.syncQueue, ^{
[_arr setObject:obj atIndexedSubscript:idx];
});
}
- (id)objectAtIndexedSubscript:(NSUInteger)idx {
__block id o;
dispatch_sync(self.syncQueue, ^{
o = [_arr objectAtIndexedSubscript:idx];
});
return o;
}
- (id)objectAtIndex:(NSUInteger)index {
__block id o;
dispatch_sync(self.syncQueue, ^{
o = [_arr objectAtIndex:index];
});
return o;
}
- (NSUInteger)count {
__block NSInteger o;
dispatch_sync(self.syncQueue, ^{
o = _arr.count;
});
return o;
}
- (void)addObject:(id)anObject {
dispatch_barrier_async(self.syncQueue, ^{
[_arr addObject:anObject];
});
}
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index {
dispatch_barrier_async(self.syncQueue, ^{
[_arr insertObject:anObject atIndex:index];
});
}
- (void)removeLastObject {
dispatch_barrier_async(self.syncQueue, ^{
[_arr removeLastObject];
});
}
- (void)removeObjectAtIndex:(NSUInteger)index {
dispatch_barrier_async(self.syncQueue, ^{
[_arr removeObjectAtIndex:index];
});
}
- (void)removeAllObjects {
dispatch_barrier_async(self.syncQueue, ^{
[_arr removeAllObjects];
});
}
- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject {
dispatch_barrier_async(self.syncQueue, ^{
[_arr replaceObjectAtIndex:index withObject:anObject];
});
}
- (NSUInteger)indexOfObject:(id)anObject {
if (!anObject) {
return NSNotFound;
}
__block NSUInteger result;
dispatch_sync(self.syncQueue, ^{
result = [_arr indexOfObject:anObject];
});
return result;
}
- (dispatch_queue_t)syncQueue {
static dispatch_queue_t queue = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSString *queuename = [NSString stringWithFormat:@"%p_com.lw.safe.mutablearray",&self];
queue = dispatch_queue_create([queuename UTF8String], DISPATCH_QUEUE_CONCURRENT);
});
return queue;
}
- (void)dealloc {
dispatch_barrier_async(self.syncQueue, ^{
[_arr removeAllObjects];
});
NSLog(@"dallalloc");
}
@end