IBOutlet for NSTextView in a ARC project

2019-03-17 13:53发布

问题:

As you read here in most cases a IBOutlet should be weak.

Now as you can read in the development library not all classes support weak references. (e.g. NSTextView). This means you have to use assign:

@property (assign) IBOutlet NSTextView *textView;

If you use a weak reference you will get the following error: "Synthesis of a weak-unavailable property is disallowed because it requires synthesis of an ivar of the __weak object"

What the documentation missed to mention is now you have to set the property again to nil after it's usage e.g. by a dealloc method:

- (void)dealloc
{
    self.textView = nil;
} 

As far as I understood classes marked with NS_AUTOMATED_REFCOUNT_WEAK_UNAVAILABLE don't support weak references but what is the reason?

回答1:

I think I found the reason why some classes don't support a weak reference:

As you can read here:

Rationale: historically, it has been possible for a class to provide its own reference-count implementation by overriding retain, release, etc. However, weak references to an object require coordination with its class's reference-count implementation because, among other things, weak loads and stores must be atomic with respect to the final release. Therefore, existing custom reference-count implementations will generally not support weak references without additional effort. This is unavoidable without breaking binary compatibility.