【发布时间】:2017-07-27 07:13:02
【问题描述】:
我正面临无法理解的内存泄漏 光纤通道
调用跟踪:
- +0x196 callq "DYLD-STUB$$NSManagedObjectContext.fetch (NSFetchRequest) throws -> [A]"
- +0x8c callq "_arrayForceCast ([A]) -> [B]"
- +0xde callq "Collection.map ((A.Iterator.Element) throws -> A1) throws -> [A1]"
- +0x19e callq "ContiguousArray.reserveCapacity(Int) -> ()"
- +0xaa callq "_ContiguousArrayBuffer.init(uninitializedCount : Int, minimumCapacity : Int) -> _ContiguousArrayBuffer"
- +0x42 callq "ManagedBufferPointer.init(_uncheckedBufferClass : AnyObject.Type, minimumCapacity : Int) -> ManagedBufferPointer"
- +0x0f callq "swift_slowAlloc"
- +0x04 callq "DYLD-STUB$$malloc"
- +0x13 callq "malloc_zone_malloc"
- +0x8f movzbl 71543(%rip), %eax
编辑:
我进一步研究了代码,我发现真正的泄漏是当我尝试在 coredata 获取请求中将类型 [Any] 强制转换为 [AnyObject] 时
func fetchEntity<T: NSManagedObject>(entityClass:T.Type,setPredicate:NSPredicate?) -> [AnyObject]
{
let entityName = NSStringFromClass(entityClass)
let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: entityName)
fetchRequest.predicate = setPredicate
fetchRequest.returnsObjectsAsFaults = false
var result:[AnyObject] = []
do
{
result = try cdh.managedObjectContext.fetch(fetchRequest) --> right here is the leak, when i cast the return object of [Any] to [AnyObject]
}catch let error as NSError
{
debugPrint("error in fetchrequest is",error)
result = []
}
return result
}
编辑: @乔恩,库巴
Model.getEntities(entityType: EX_TEACHER.self, completion: {[unowned self] entityobjects in
self.teacherList = entityobjects
})
//在模型类中
class func getEntities<T: NSManagedObject>(entityType: T.Type,completion: ([AnyObject]) -> Void)
{
let teacherList = coreDataOperation.fetchEntity(entityClass: entityType, setPredicate: nil)
completion(teacherList)
}
// cdh.managedObjectContext 代码
lazy var cdh:CoreDataStore = {
let cdh = CoreDataStore()
return cdh
}()
class CoreDataStore: NSObject{
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}() }
【问题讨论】:
-
当你调用这个 fetchEntity 函数时,请粘贴一个代码。你在执行选择器?取 unretainedValue?
-
您使用哪个上下文进行抓取?刚刚为这个 fetch 创建了什么?
-
用请求的代码编辑。
标签: ios swift core-data memory-leaks swift3