简体   繁体   中英

When do you have to use @property and @synthesize in the iPhone SDK?

When do you have to use @property and @synthesize in the iPhone SDK? And why use @property and @synthesize ? I was studying property, but I can't get a correct idea. What would some examples for illustrating this be?

@property : you used it when you want to:

You can use some of the really useful generated code like nonatomic, atmoic, retain without writing any lines of code. You also have getter and setter methods. To use this, you have 2 other ways: @synthesize or @dynamic: @synthesize, compiler will generate the getter and setter automatically for you, @dynamic: you have to write them yourself.

@property is really good for memory management, for example: retain.

How can you do retain without @property?

  if (_variable != object) {
    [_variable release];
    _variable = nil;
    _variable = [object retain];
  }

How can you use it with @property?

self.variable = object;

When you are calling the above line, you actually call the setter like [self setVariable:object] and then the generated setter will do its job

@property (along with @synthesize) automatically generates set and/or get code. So the following code:

self.prop = @"some string";

is equivalent to

[self setProp: @"some string"];

Note also,

self.prop = @"some string";

is different from

prop = @"some string";

The latter sets the variable directly, whereas the former calls the method getProp to set the variable prop .

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