Swift Array was deallocated when used in dispatch_apply_f function (introduced in iOS 16)

When passing Swift array to initialize Buffer, obj-C bridging creates DeferredNSArray, which defers creating of obj-c BridgingBuffer till the first access to the elements of array is made. Since we are initializing our Buffer’s internal storage in parallel, we end up in a situation where BridgingBuffer is created from several threads and we have got the crash. Please see attached screenshot and files. Can you help me to fix this issue?

Try doing this:

- (instancetype)initWithArray:(NSArray *)array {
    self = [super init];
    if (self) {
        NSArray * array2 = [array copy];
        mapTo(cBuffer, [&](size_t i) {
            cBuffer[i] = (size_t)array2[i];
            std::cout << i << std::endl;
        });
    }
    return self;
}

Your code as it stands is not safe Objective-C. NSArray is intended to be subclassed, most notably by NSMutableArray. When you receive an array from ‘outside’, you don’t know what specific type of array you’ve got and thus the standard idiom is to copy it.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Dear Eskimo, thanks for your answer. I tried your solution but I still got the same crash. Please note that this sample works on previous iOS versions but in the latest iOS 16 I'm getting this strange crash.

Please note that this sample works on previous iOS versions but in the latest iOS 16 I'm getting this strange crash.

Did you file a bug about that? It’s definitely worth doing that for regressions like this.

Please post your bug number, just for the record.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Swift Array was deallocated when used in dispatch_apply_f function (introduced in iOS 16)
 
 
Q