Is there a template for working with resources without memory when cleaning an ObjC object?

Usually for objects that have some state related to a resource without memory, to provide a method for explicitly "terminating" this resource. Is there a preferred common practice to consider when an attempt to free an object is made while maintaining the “use my resource” state? I have seen several different approaches:

  • log that the programmer made a mistake and told them how to debug it ( NSLock does this)
  • let the caller choose whether the resource is being managed by the caller or refuses to free (for example, NSFileHandle )
  • throws an exception if the object is not in the expected final state, i.e. claims that the programmer will not use my object in this way
  • always get out.

GC docs confirm that managing other resources along with memory management is a “Bad Idea” and (for now) - Example 4, albeit with reservations. So did someone choose the approach that always follows?

+4
source share
1 answer

Since most Cocoa structure objects precede garbage collection, you cannot assume that NSFileHandle, for example, does it in the best way. I think this problem is one of many where we would like to have one template for each scenario and save us from having to choose. Unfortunately, I do not think this is possible; You will need to determine what is best for each case.

Below are the reasons for choosing any of your options:

  • If automatic cleaning is safe enough, but the program really needs to do it manually.
  • If you are writing a library, and the resource may or may not belong to your object.
  • If automatic cleaning is not possible or somehow risky.
  • If automatic cleaning is trivial and you don’t have to bother anyone to do it manually.
+1
source

Source: https://habr.com/ru/post/1277687/


All Articles