How to write my own setter for an ivar, i.e.: self.ivar = …?

前端 未结 2 924
抹茶落季
抹茶落季 2021-01-06 19:04

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

相关标签:
2条回答
  • 2021-01-06 19:56

    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];
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-06 19:56

    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

    0 讨论(0)
提交回复
热议问题