1

According to Apple developer site:Practical Memory Management, in the implementation of custom set method of the retain property is as follows:

@interface Counter : NSObject
@property (nonatomic, retain) NSNumber *count;
@end;

- (void)setCount:(NSNumber *)newCount {
    [newCount retain];
    [_count release];
    // Make the new assignment.
    _count = newCount;
}

But many website suggest the first step should be release. For example, in this question:objective c - Explicit getters/setters for @properties (MRC) - Stack Overflow, the answer gives another implementation.

 - (void)setCount:(NSNumber *)count {
    if (count != _count) {
        NSNumber *oldCount = _count;
        // retain before releasing the old one, in order to avoid other threads to
        // ever accessing a released object through the `_count` pointer.
        _count = [count retain];
        // safely release the old one.
        [oldCount release];
    }
}

So I'm doubt the difference between these two implementation. Which one is preferred and why?

Thanks for your attention and answer.

doit
  • 29
  • 3
  • 1
    May be just turn-on ARC? – Cy-4AH Sep 20 '19 at 10:43
  • Do you have arguments why some sites suggests releasing first? In your's second snippet `release` also called after `retain` – Cy-4AH Sep 20 '19 at 10:52
  • ARC follows the second snippet (including the test as mentioned in another answer). Decide for yourself whether that makes it "preferred". – CRD Sep 22 '19 at 02:56
  • @Cy-4AH Here is a website which suggest release first. https://stackoverflow.com/questions/5040702/when-declare-a-propertyretain-in-objective-c-whats-the-default-implementatio – doit Oct 17 '19 at 02:22

2 Answers2

3

The difference is subtle, but if you assign a value to itself then you could release the object:

id x = self.thing;
self.thing = x;

So the ethos was always to retain the new first and release the old after.

Turn on ARC and this nonsense all goes away.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
0

I don't really see any argument of why retain would be called after release. I could however find arguments why not to release it first.

If you release the old object first it might happen that the new object will be released and deallocated with it. It would be a very specific situation but it could happen. Not with NSNumber obviously but think for instance that this is a UIView and a new value is a subview of the old value. Now old value has a reference to the new value and it retains it. By releasing the old value you surely reduce retain count on the new value. For the retain count to fall to zero and object be released must be a bit special situation as well but again, it could make sense.

So in general when you get an object you must first retain it. After that you can start modifying any other data.

Matic Oblak
  • 16,318
  • 3
  • 24
  • 43