How to write a wrapper around CFSomeRef

I am testing with FSEventStreamCreate which returns an FSEventStreamRef, but I cannot find an equivalent toll-free class in Cocoa.

In order to free-up resources used by this Ref, I need to do following:

        FSEventStreamStop(stream);
        FSEventStreamInvalidate(stream);
        FSEventStreamRelease(stream);

That is quite error-prone and tedious. So I want to write a wrapper class, but don't have any idea on when or where to release the Ref. Is it correct to do 'free' in dealloc?

Accepted Reply

Is it correct to do 'free' in dealloc?

Possibly. There are two patterns that I commonly use here:

  • Explicit invalidate (A)

  • Invalidate in -dealloc (B)

Option B is what you’re describing. For ‘expensive’ tasks like this, I generally lean towards option A because then I control exactly when the task stops. With option B it’s easy to ‘leak’ a reference to the object, which prevents the task from stopping, which would be bad.

If I do A, I also add an assert in -dealloc that the invalidation has actually happened. That helps catch bugs where you forget to invalidate.

Finally, there’s a hybrid:

  • Support explicit invalidation but also invalidate in -dealloc if that wasn’t done (C)

Lots of folks use this but I’m not a fan because it’s more code for little practical benefit.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Replies

Is it correct to do 'free' in dealloc?

Possibly. There are two patterns that I commonly use here:

  • Explicit invalidate (A)

  • Invalidate in -dealloc (B)

Option B is what you’re describing. For ‘expensive’ tasks like this, I generally lean towards option A because then I control exactly when the task stops. With option B it’s easy to ‘leak’ a reference to the object, which prevents the task from stopping, which would be bad.

If I do A, I also add an assert in -dealloc that the invalidation has actually happened. That helps catch bugs where you forget to invalidate.

Finally, there’s a hybrid:

  • Support explicit invalidation but also invalidate in -dealloc if that wasn’t done (C)

Lots of folks use this but I’m not a fan because it’s more code for little practical benefit.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"