Issue when appending a CTFrame to a Swift Array

百般思念 提交于 2019-12-12 01:37:42

问题


I have a CoreText that works in Objective-C and the migration to Swift is driving me nuts.

This is the (simplified) code:

var ctFramesArray: Array<CTFrame> = CTFrame[]()

ctFramesArray.append(ctFrame)

The ctFrame is a valid object. I can inspect it with the debugger, println() it, and the project runs fine rendering the CoreText columns properly.

The ctFramesArray reports zero objects after being created and before appending the first ctFrame object.

But I have a run time error (EXEC_BAD_ACCESS) when trying to append the ctFrame to the Array.

It seems that is is an assertion failure, but I can´t figure out what it is

UPDATE:

This behaviour is strange

I have the following cases:

    var ctFramesArray: Array<CTFrame> = Array<CTFrame>()
    ctFramesArray.append(ctFrame)
    println(ctFramesArray.count)

The ctFramesArray.append(ctFrame) line works fine when the ctFramesArray is local (within the function), but if it is a global variable, I get the run time EXEC_BAD_INSTRUCTION error.

I tested this using an array of strings as follows and it works with the array being declared locally or globally. It seems that the issue is related to the CTFrame type (the ctFrame object is valid and the frames are rendered correctly)

    var stringsArray: Array<String> = Array<String>()
    stringsArray.append("One")
    println(stringsArray.count)

Any clue?


回答1:


It's probably an issue related to the ARC ref count for the CTFrame. How did you obtain ctFrame? I suspect ctFrame has a shorter lifetime than ctFramesArray and that will cause a crash.




回答2:


I found a fix to the problem

If the global variable ctFramesArray is defined "globally" as an array of CTFrame objects, then we get the run time error. But if the array is defined as an array of AnyObject, as follows, then the issue is fixed:

var ctFramesArray: Array<AnyObject> = Array<AnyObject>()

There seems to be an issue with the AnyObject compatibility in the CTFrame object.

The puzzling part is still the fact that with the array declared locally as Array, the declaration works fine

... e



来源:https://stackoverflow.com/questions/24442722/issue-when-appending-a-ctframe-to-a-swift-array

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