0

We have an Objective C library that creates objects that are meant to be used in Swift code.

The function returns the object as an id. This is the declaration in Objective C header file (Clazz.h). The header file has been exposed in bridging header as required for interoperability.

+ (id)getObject;

The pointer returned is an instance of AVAssetWriter*. To access this API in Swift, I followed the steps in below post: Objective-C pointer and swift

This is the Swift 3 code consumer code:

let obj = (Clazz.getObject() as! UnsafeMutableRawPointer).assumingMemoryBoundTo(to: AVAssetWriter.self).pointee

It built fine. However, when this code executes, the app seems to crash.

In Clazz.h, I declared the function as:

+ (AVAssetWriter*)getObject();

and tried to use it in Swift as,

let obj = Clazz.getObject() as AVAssetWriter

Code built fine but it failed when it was executed.

How do we access Objective C created objects in Swift?

Please note that I was able to inspect the value in swift code and the problem is not in bridging. Also, the memory location is not dangling.

user3911119
  • 273
  • 3
  • 14
  • The obvious answer is to rewrite the Objective C declaration so that it returns the actual type rather than `id`. You say that `as AVAssetWriter` failed at runtime. What happened? How did it fail? – Paulw11 Jul 28 '18 at 07:27
  • sorry... it did not fail there. The typecast worked but on inspecting it, it shows a long value and ObjectiveC.NSObject & not AVAssetWriter. It failed when I tried to use it as AVAssetWriter and accessed one of it's properties. – user3911119 Jul 28 '18 at 07:37
  • So what was *that* error when you attempted to access the property? – Paulw11 Jul 28 '18 at 07:39
  • I found the issue... as a java developer, I was so used to declaring the type with the variable name that I forgot to mention obj as of type AVAssetWriter. Thanks! – user3911119 Jul 28 '18 at 07:54
  • I’m not sure. Perhaps ask another question showing your code and the exact message from the compiler – Paulw11 Jul 28 '18 at 08:45
  • yes... will do. thanks! – user3911119 Jul 28 '18 at 09:51

1 Answers1

0

By declaring obj variable as below, things worked

let obj:AVAssetWriter = Clazz.getObject() as AVAssetWriter
user3911119
  • 273
  • 3
  • 14