Páginas

Monday, August 30, 2010

Accessor Methods

Following my last post, I'm going to talk a little bit about the accessor methods in Objective-C.

Accessor methods, as you may know, are those methods used to get or set the value of an object's variable, without actually "seeing" it. As you might imagine these methods are used many times in most, if not all, object-oriented programming languages. Objective-C 2.0 provides a very elegant way to declare these methods and saving a lot of lines of code.

It uses the key words @property and @synthesize. In general, a declaration of a property looks like this:

@property (attributes) type name;

The attributes can include readwrite (default) or readonly (doesn't get a setter method). To describe how the setter works it can also include assign, retain or copy.
  • assign (default) - simple assignment, does not retain the new value. If it's an object type and you're not using the GC, don't use this.
  • retain - releases the old value and retains the new. With GC is the same as assign.
  • copy - makes a copy of the new value and assigns the variable to the copy. (often used for strings).
So, a property declaration in the header file should look something like this:


@interface ClassName : NSObject {
    int foo;
}
@property (readwrite,assign) int foo;
@end


And then, in the implementation file you just need to write @synthesize foo; and your accessor methods are defined.

NOTE: There are two ways of using these methods, the normal one is by sending a
message to the object:

[object setValue:newValue];

and there is the other way, that's called the dot syntax and is a lot like what you do in Java:

object.value = newValue;

Although you can use the dot syntax, I do not recommend it. Read this post for the reasons why.

No comments: