3

This is a follow-up question of: Difference between self.ivar and ivar? :

self.name = @"hello";

I would like to know what is done inside the magical setter method. So the question is: could anyone please post the source code of the setter method? ;-) Thanks!

Community
  • 1
  • 1
ohho
  • 47,708
  • 70
  • 236
  • 372
  • Your question title doesn't match what is explained in your question content... – BoltClock Nov 11 '10 at 02:47
  • 1
    See [here](http://stackoverflow.com/questions/588866/objective-c-properties-atomic-vs-nonatomic/589348#589348) for another version. Also note that it doesn't matter what the actual implementation looks like, you only need to know what effects it has. – Georg Fritzsche Nov 11 '10 at 02:56

2 Answers2

11

Without a property declaration (that is, you have manually declared the setter and getter methods), you'd typically implement them like this:

@interface MyClass : NSObject
{
    NSString *name;
}
- (NSString *) name;
- (void) setName:(NSString *) name;
@end

@implementation MyClass

- (void) dealloc
{
    [name release];
    [super dealloc];
}

- (NSString *) name
{
    return name;
}

- (void) setName:(NSString *) aName
{
    if (aName != name)
    {
        [name release];
        name = [aName retain];
    }
}

@end

Atomic setters could look something like this:

- (void) setName:(NSString *) aName
{
    @synchronized(self)
    {
        if (aName != name)
        {
            [name release];
            name = [aName retain];
        }
    }
}
Georg Fritzsche
  • 93,086
  • 26
  • 183
  • 232
dreamlax
  • 89,489
  • 28
  • 156
  • 207
3

The basic answer is that you need to define a method called "setXXX:" where "XXX" is the name of your property, starting with a capital letter, e.g. if your property is called "name", then your setter should be called "setName:". In this method, you should make the assignment of the argument to your actual ivar.

That said, dreamlax is correct in that there is more to it. When you declare your property, you define a contract regarding how the assignment will work regarding things like thread-safety and memory management. Apple has great documentation on this subject, and I suggest you check it out:

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProperties.html%23//apple_ref/doc/uid/TP30001163-CH17-SW14

Ryan
  • 16,296
  • 2
  • 21
  • 20