Wednesday, September 6, 2017 [Tweets] [Favorites]

Swift and KVO Context Variables

Michael Brown:

I found the solution to the problem in this Apple Swift Blog post about interacting with C pointers from July 2014! So this has been a problem right since the start of Swift, but only now, perhaps with improved runtime checks in Swift 4, is it causing crashes.

The relevant part is here (emphasis mine):

These conversions cannot safely be used if the callee saves the pointer value for use after it returns. The pointer that results from these conversions is only guaranteed to be valid for the duration of a call. Even if you pass the same variable, array, or string as multiple pointer arguments, you could receive a different pointer each time. An exception to this is global or static stored variables. You can safely use the address of a global variable as a persistent unique pointer value, e.g.: as a KVO context parameter.

The best fix is probably to use the new KVO API, but this issue is worth keeping in mind for other APIs that use C pointers.

Update (2017-09-06): Joe Groff:

That use case should work with the latest Xcode 9 betas.

I forget details, but exclusivity enforcement for passing pointers to ivars was relaxed to accommodate this kind of use.

Comments

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment