Leaks in Swift 3 / iOS 10

白昼怎懂夜的黑 提交于 2019-11-29 10:37:11

I had the same problem and spent a lot of time digging. I found that if you create a Swift object from Objective-C code and the Swift object has a native Swift dictionary property, you will see this leak. It won't happen if all the code is Swift, and more usefully, it won't leak if you change the native Swift dictionary to an NSDictionary. This also applies to Swift Set's and NSSet's. I also saw that the leak happens on iOS 10 and not on iOS 9.

// LeakySwiftObject.swift
class LeakySwiftObject: NSObject {
    let dict = [String: String]() // <- Any native Swift dictionary will reproduce the leak
}

// ObjectiveCObject.h
@class LeakySwiftObject;

@interface ObjectiveCObject : NSObject
@property (strong) LeakySwiftObject *leaky;
@end

// ObjectiveCObject.m
@implementation ObjectiveCObject

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.leaky = [LeakySwiftObject new];
    }
    return self;
}

@end

// ViewController.swift
class ViewController: UIViewController {
    let testObj = ObjectiveCObject()
}

The Leaks Instrument reports a leak:
_NativeDictionaryStorageImpl<String,String>
_NativeDictionaryStorageOwner<String,String>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!