简体   繁体   中英

How to manage object when override setter in ARC?

I have question when I override setter for a @property.

that is:

If I set a property like this :

@property (strong) NSString *name;

In 'MRC' it will auto-generate getter and setter, assume setter will implement like this :

- (void)setName:(NSString *)name
{
    [_name release]; // Release previous.
    _name = name;
    [_name retain];  // Remain object.
}

When I override setter in 'MRC', I can manage object by follow 'strong' behavior like code above,

but when in 'ARC', what will setter implement like or how to manage object to make it behavior like 'strong' since it has no 'retain and release' in 'ARC' ?

Thanks for yor time!

Under ARC, the compiler generates this setter:

- (void)setName:(NSString *)name {
    _name = name;
}

But since _name is declared __strong (because the property is strong ), the assignment turns into a call to objc_storeStrong :

- (void)setName:(NSString *)name {
    objc_storeStrong(&_name, name);
}

The objc_storeStrong function takes care of the retain and release, and does so more safely than yours:

id objc_storeStrong(id *object, id value) {
  value = [value retain];
  id oldValue = *object;
  *object = value;
  [oldValue release];
  return value;
}

(Consider what happens in your setter if name == _name and its retain count is 1 at the start of the setter. The objc_storeStrong function is also carefully written to avoid race conditions when multiple threads try to set the property simultaneously.)

ARC doesn't really require that you do anything special or additional, except for explicit bridging to Core Foundation pointers (which the compiler can auto-fix). It mainly requires that you don't write memory management code (like retain/release calls) yourself. You really don't need to "learn ARC", you only need to learn the memory issues that ARC cannot handle for you, like retain cycles (bad) and the management of C pointers (ie Core Foundation types--except when called from Swift, in which case ARC can handle them as well). The whole point of ARC is automating a part of software development that is very tedious and error-prone; it's less for you to worry about, not more. As an analogy, you don't really need to know anything about SQL in order to use Core Data...the finer details are abstracted away for you.

You made the property strong by virtue of declaring it strong, there isn't anything special you have to do in the setter:

-(void)setName:(NSString*)name
{
    _name = name;
}

Of course, that is a silly example because there is no reason to override a setter when all you're doing is the default behavior, anyway. But you get the point...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM