[swift-dev] Question: memory management on Stack with Structs ?

Greg Parker gparker at apple.com
Thu Oct 19 03:37:26 CDT 2017



> On Oct 18, 2017, at 6:05 PM, Thibault Wittemberg via swift-dev <swift-dev at swift.org> wrote:
> 
> Hi everyone,
> 
> I am a member of the RxSwiftCommunity, and I am facing an issue on a PR that I've made (https://github.com/RxSwiftCommunity/NSObject-Rx/pull/49 <https://github.com/RxSwiftCommunity/NSObject-Rx/pull/49>).
> 
> The big picture is:
> I have a protocol that declares a computed var (get set) with a default implementation that uses the "objc_setAssociatedObject(self, &disposeBagContext, disposeObject, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)" primitive to store and retrieve its value.
> Here is the complete code:
> public protocol HasDisposeBag {
>     /// a unique RxSwift DisposeBag instance
>     var disposeBag: DisposeBag { get set }
> }
> extension HasDisposeBag {
>     func synchronizedBag<T>( _ action: () -> T) -> T {
>         objc_sync_enter(self)
>         let result = action()
>         objc_sync_exit(self)
>         return result
>     }
>     public var disposeBag: DisposeBag {
>         get {
>             return synchronizedBag {
>                 if let disposeObject = objc_getAssociatedObject(self, &disposeBagContext) as? DisposeBag {
>                     return disposeObject
>                 }
>                 let disposeObject = DisposeBag()
>                 objc_setAssociatedObject(self, &disposeBagContext, disposeObject, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
>                 return disposeObject
>             }
>         }
>         set {
>             synchronizedBag {
>                 objc_setAssociatedObject(self, &disposeBagContext, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
>             }
>         }
>     }
> }
> 
> The question is: what happens when it is a struct that conforms to this protocol ?

Nothing good. It is unsafe to use objc_setAssociatedObject() with a Swift struct. For that matter you can't use objc_sync_enter/exit either.


-- 
Greg Parker     gparker at apple.com     Runtime Wrangler


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-dev/attachments/20171019/cbb72146/attachment.html>


More information about the swift-dev mailing list