I have a class that uses automatic reference counting. Within the class, I have a property as described below. When I set the reminder for the class, I want the side effect of changing the button title to take place.
Here’s my code:
in the .h file:
@property(nonatomic,strong)Reminder* reminder;
in the .m file:
@synthesize reminder;
-(void)setReminder:(Reminder *)reminder_
{
//what else do I need to do here?
reminder = reminder_;
if(!reminder.useSound.boolValue)
{
onOffButton.title = NSLocalizedString(@"Off", @"Off title");
}else
{
onOffButton.title = NSLocalizedString(@"On", @"On title");
}
}
I know that without ARC I would do something like this:
-(void)setReminder:(Reminder *)reminder_
{
[reminder release];
reminder = [reminder_ retain];
if(!reminder.useSound.boolValue)
{
onOffButton.title = NSLocalizedString(@"Off", @"Off title");
}else
{
onOffButton.title = NSLocalizedString(@"On", @"On title");
}
}
Do I need to do anything else within my ARC enabled setter method to ensure that the strong variable is retained properly?
You don’t need to write your own setter for side effects like this. Use KVO!
Make the controller that owns the button observe this object’s
reminderproperty:The
optionsargument specifies what information about the state of the observed object you’d like passed along when the observation is made.Then your controller will be apprised whenever this property changes value (note that this will only occur if the property is set in a “Key-Value compliant” manner, the handiest way being via the setter method* — changing the ivar directly doesn’t count).
You need to implement
observeValueForKeyPath:ofObject:change:context:in your controller:Oh, and to, uh, answer your actual question, I believe that your memory management is fine.
reminderis synthesized to be a__strong-qualified variable, which means ARC will retain whatever you put there.*Which is why you’ve heard not to use setters in
initanddealloc.