Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 38 ยท Objects and Classes

Properties

Learn @property declarations, generated accessors and ivars, attributes such as strong, weak, copy, nonatomic and readonly, dot syntax, and custom getters and setters.

Almost every class exposes some state. Writing a getter and a setter for each value by hand is repetitive, so Objective-C 2.0 introduced properties. A single @property line declares the accessor methods, and the compiler synthesizes the instance variable and the method bodies. Property attributes tell the compiler how the value is stored: whether the object is owned, copied, shared, or read-only. Choosing them correctly is one of the most important skills in the language.

Declaring a property

OBJECTIVEC
@interface Person : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, readonly) NSString *displayName;

@end

For name the compiler generates:

  • an instance variable _name,
  • a getter - (NSString *)name,
  • a setter - (void)setName:(NSString *)name (not for readonly properties).

You do not write @synthesize in modern code: automatic synthesis is the default.

Dot syntax

The dot is shorthand for the accessor messages:

OBJECTIVEC
Person *p = [[Person alloc] init];
p.name = @"Ada";           // [p setName:@"Ada"]
NSString *n = p.name;      // [p name]
p.age += 1;                // [p setAge:[p age] + 1]

Use dot syntax for properties and brackets for everything else. Dot syntax on a nil object is safe in the same way messages are. Inside the class, using self.name goes through the accessors and _name reads the variable directly. Initializers and dealloc conventionally use the ivar, to avoid side effects of overridden setters.

Attributes

Ownership attributes (objects)

Attribute Meaning
strong The property owns the object and keeps it alive (the default for objects under ARC).
weak Does not own it; automatically becomes nil when the object is freed. For delegates and parent pointers.
copy Stores a private copy via copy. Use for NSString, NSArray, NSDictionary and blocks.
assign Plain assignment, for primitives like NSInteger, BOOL, CGFloat.
unsafe_unretained Like weak but not zeroed. Rare.

Why copy for strings? Someone could pass an NSMutableString and mutate it later, changing your property behind your back. copy of an immutable string is free (it just retains), and of a mutable one makes a snapshot.

Access attributes

  • readwrite (default) creates getter and setter.
  • readonly creates only a getter. A class can redeclare it readwrite in its private class extension, so that it can change the value internally while outsiders only read it.

Thread safety

  • nonatomic skips locking in the accessor. It is faster, and the standard for UI and most code.
  • atomic (the default if you write nothing) makes single reads and writes of the pointer atomic, but does not make your class thread safe. Always write nonatomic explicitly.

Custom names

OBJECTIVEC
@property (nonatomic, getter=isEnabled) BOOL enabled;
@property (nonatomic, setter=setActive:) BOOL active;
@property (nonatomic, class) NSInteger instanceCount;   // class property

With getter=isEnabled you can write view.enabled but the generated method is isEnabled.

Nullability

Annotations help Swift and static analysis: @property (nonatomic, copy, nullable) NSString *nickname; and nonnull for values that must exist. A region can be wrapped in NS_ASSUME_NONNULL_BEGIN and NS_ASSUME_NONNULL_END.

Custom accessors

You may implement the getter or setter yourself for validation or side effects. If you override both a readwrite property's accessors, the compiler no longer synthesizes the ivar, so add @synthesize name = _name;:

OBJECTIVEC
- (void)setAge:(NSInteger)age {
    _age = MAX(age, 0);        // never negative
}

- (NSString *)displayName {    // computed readonly property, no ivar
    return [NSString stringWithFormat:@"%@ (%ld)", self.name, (long)self.age];
}

A computed property has no storage; it derives its value from other state.

Properties and ARC memory

A strong property retains what is assigned and releases the old value. A weak property does not retain, and a retain cycle can form if two objects hold each other strongly. The classic fix: the parent holds the child strong, the child holds the parent weak. Chapter 5 explains this in depth.

Stand-in: accessors, ownership by copy and validation

Properties are accessor functions over a hidden field. This stand-in shows a setter that validates, a getter that computes a value, and the reason copy matters: storing a copy keeps your data safe from later changes.

C Stand-in (C): setter validation and copy semantics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: readonly outside, writable inside

A readonly property exposed publicly but written privately means only the class's own functions change the value. The C stand-in uses a header-style declaration with only a getter, and a private setter used internally.

C Stand-in (C): public getter, private setter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Common mistakes

  • Using strong for NSString properties instead of copy.
  • Using strong for delegates, creating retain cycles. Use weak.
  • Forgetting nonatomic and paying for locks that do not give thread safety.
  • Using dot syntax for non-property methods, such as array.count on a custom method.
  • Implementing both accessors by hand and then finding that _name no longer exists.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which attribute should you use for an NSString property?

    copy protects against a mutable string being changed later by the caller.
  2. 2. What does p.name = @"Ada"; translate to?

    Dot assignment calls the setter message.
  3. 3. Which attribute is correct for a delegate property?

    A delegate should be weak so that two objects do not retain each other.
  4. 4. What does the compiler synthesize for @property (nonatomic, copy) NSString *title;?

    Automatic synthesis creates the backing variable and both accessors for a readwrite property.

Summary

  • @property declares accessors; the compiler synthesizes _name, getter and setter.
  • Dot syntax is shorthand for the accessor messages.
  • Use copy for strings and collections, weak for delegates and back-references, assign for primitives.
  • Write nonatomic explicitly; atomic does not make a class thread safe.
  • A readonly public property can be made readwrite in a class extension.

Next: Initializers and dealloc