forked from fullonrager/rys-objective-c-tutorial-archive
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproperties.html
More file actions
685 lines (510 loc) · 35.7 KB
/
properties.html
File metadata and controls
685 lines (510 loc) · 35.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Properties - Ry’s Objective-C Tutorial - RyPress</title>
<meta charset='UTF-8' />
<meta name='description' content="An object’s properties let other objects inspect or change its state.
But, in a well-designed object-oriented program, it’s not possible to
directly access the internal state of an object. Instead, accessor
methods (getters and setters) are used as an abstraction for
interacting with the object’s underlying data." />
<meta name='viewport'
content='width=device-width, initial-scale=1.0, maximum-scale=1.0' />
<link rel="icon" type="image/png" href="media/favicon.png" />
<link rel="stylesheet" href="media/style.css" />
<link rel="stylesheet" href="media/pygments.css" />
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-37121774-2', 'auto');
ga('send', 'pageview');
</script>
</head>
<body>
<div id='page'>
<div id='content'>
<nav id='main-nav'>
<a href='/'><img src='media/logo-small.png'
width='120px'
alt='RyPress - Quality Software Tutorials'/></a>
<ul>
<li><a href='/'>Tutorials</a></li>
<li><a href='/secure/purchases.php'>Purchases</a></li>
<li><a href='/about.php'>About</a></li>
</ul>
</nav>
<div class='divider'></div>
<table class="icon-and-text"><tr>
<td><a href="index"><img src="media/icons/index.png" width="40px" height="40px"></a></td>
<td><p>You’re
reading
<a href="index.html"><em>Ry’s Objective-C Tutorial</em></a></p></td>
</tr></table><div class="divider"></div>
<h1 id="properties">Properties</h1>
<p>An object’s properties let other objects inspect or change its state.
But, in a well-designed object-oriented program, it’s not possible to
directly access the internal state of an object. Instead, <strong>accessor
methods</strong> (getters and setters) are used as an abstraction for
interacting with the object’s underlying data.</p>
<figure>
<img style="max-width: 320px" src="media/properties/accessor-methods.png">
<figcaption>Interacting with a property via accessor methods</figcaption>
</figure>
<p>The goal of the <code>@property</code> directive is to make it easy to
create and configure properties by automatically generating these accessor
methods. It allows you to specify the behavior of a public property on a
semantic level, and it takes care of the implementation details for you.</p>
<p>This module surveys the various attributes that let you alter getter and
setter behavior. Some of these attributes determine how properties handle their
underlying memory, so this module also serves as a practical introduction to
memory management in Objective-C. For a more detailed discussion, please refer
to <a href="memory-management.html">Memory Management</a>.</p>
<h2 id="the-property-directive">The @property Directive</h2>
<p>First, let’s take a look at what’s going on under the hood when
we use the <code>@property</code> directive. Consider the following interface
for a simple <code>Car</code> class and its corresponding implementation.</p>
<pre><code class="c1">// Car.h</code>
<code class="cp">#import</code> <code class="l"><Foundation/Foundation.h></code><code class="cp"></code>
<code class="k">@interface</code> <code class="nc">Car</code> : <code class="nc">NSObject</code>
<code class="k">@property</code> <code class="kt">BOOL</code> <code class="n">running</code><code class="p">;</code>
<code class="k">@end</code>
</pre>
<pre><code class="c1">// Car.m</code>
<code class="cp">#import</code> <code class="l">"Car.h"</code><code class="cp"></code>
<code class="k">@implementation</code> <code class="nc">Car</code>
<code class="k">@synthesize</code> <code class="n">running</code> <code class="o">=</code> <code class="n">_running</code><code class="p">;</code> <code class="c1">// Optional for Xcode 4.4+</code>
<code class="k">@end</code>
</pre>
<p>The compiler generates a getter and a setter for the <code>running</code>
property. The default naming convention is to use the property itself as the
getter, prefix it with <code>set</code> for the setter, and prefix it with an
underscore for the instance variable, like so:</p>
<pre><code class="k">-</code> <code class="p">(</code><code class="kt">BOOL</code><code class="p">)</code><code class="nf">running</code> <code class="p">{</code>
<code class="k">return</code> <code class="n">_running</code><code class="p">;</code>
<code class="p">}</code>
<code class="k">-</code> <code class="p">(</code><code class="kt">void</code><code class="p">)</code><code class="nf">setRunning:</code><code class="p">(</code><code class="kt">BOOL</code><code class="p">)</code><code class="nv">newValue</code> <code class="p">{</code>
<code class="n">_running</code> <code class="o">=</code> <code class="n">newValue</code><code class="p">;</code>
<code class="p">}</code>
</pre>
<p>After declaring the property with the <code>@property</code> directive, you
can call these methods as if they were included in your class’s interface
and implementation files. You can also override them in <code>Car.m</code> to
supply custom getter/setters, but this makes the <code>@synthesize</code>
directive mandatory. However, you should rarely need custom accessors, since
<code>@property</code> attributes let you do this on an abstract level.</p>
<p>Properties accessed via dot-notation get translated to the above accessor
methods behind the scenes, so the following <code>honda.running</code> code
actually calls <code>setRunning:</code> when you assign a value to it and the
<code>running</code> method when you read a value from it:</p>
<pre><code class="c1">// main.m</code>
<code class="cp">#import</code> <code class="l"><Foundation/Foundation.h></code><code class="cp"></code>
<code class="cp">#import</code> <code class="l">"Car.h"</code><code class="cp"></code>
<code class="kt">int</code> <code class="nf">main</code><code class="p">(</code><code class="kt">int</code> <code class="n">argc</code><code class="p">,</code> <code class="kt">const</code> <code class="kt">char</code> <code class="o">*</code> <code class="n">argv</code><code class="p">[])</code> <code class="p">{</code>
<code class="k">@autoreleasepool</code> <code class="p">{</code>
<code class="n">Car</code> <code class="o">*</code><code class="n">honda</code> <code class="o">=</code> <code class="p">[[</code><code class="n">Car</code> <code class="nf">alloc</code><code class="p">]</code> <code class="nf">init</code><code class="p">];</code>
<code class="n">honda</code><code class="p">.</code><code class="n">running</code> <code class="o">=</code> <code class="kc">YES</code><code class="p">;</code> <code class="c1">// [honda setRunning:YES]</code>
<code class="nb">NSLog</code><code class="p">(</code><code class="s">@"%d"</code><code class="p">,</code> <code class="n">honda</code><code class="p">.</code><code class="n">running</code><code class="p">);</code> <code class="c1">// [honda running]</code>
<code class="p">}</code>
<code class="k">return</code> <code class="mi">0</code><code class="p">;</code>
<code class="p">}</code>
</pre>
<p>To change the behavior of the generated accessors, you can specify
attributes in parentheses after the <code>@property</code> directive. The rest
of this module introduces the available attributes.</p>
<h2 id="the-getter-and-setter-attributes">The getter= and setter= Attributes</h2>
<p>If you don’t like <code>@property</code>’s default naming
conventions, you can change the getter/setter method names with the
<code>getter=</code> and <code>setter=</code> attributes. A common use case for
this is Boolean properties, whose getters are conventionally prefixed with
<code>is</code>. Try changing the property declaration in <code>Car.h</code> to
the following.</p>
<pre><code class="k">@property</code> <code class="p">(</code><code class="k">getter</code><code class="o">=</code><code class="n">isRunning</code><code class="p">)</code> <code class="kt">BOOL</code> <code class="n">running</code><code class="p">;</code>
</pre>
<p>The generated accessors are now called <code>isRunning</code> and
<code>setRunning</code>. Note that the public property is still called
<code>running</code>, and this is what you should use for dot-notation:</p>
<pre><code class="n">Car</code> <code class="o">*</code><code class="n">honda</code> <code class="o">=</code> <code class="p">[[</code><code class="n">Car</code> <code class="nf">alloc</code><code class="p">]</code> <code class="nf">init</code><code class="p">];</code>
<code class="n">honda</code><code class="p">.</code><code class="n">running</code> <code class="o">=</code> <code class="kc">YES</code><code class="p">;</code> <code class="c1">// [honda setRunning:YES]</code>
<code class="nb">NSLog</code><code class="p">(</code><code class="s">@"%d"</code><code class="p">,</code> <code class="n">honda</code><code class="p">.</code><code class="n">running</code><code class="p">)</code><code class="o">;</code> <code class="c1">// [honda isRunning]</code>
<code class="nb">NSLog</code><code class="p">(</code><code class="s">@"%d"</code><code class="p">,</code> <code class="p">[</code><code class="n">honda</code> <code class="nf">running</code><code class="p">])</code><code class="o">;</code> <code class="c1">// Error: method no longer exists</code>
</pre>
<p>These are the only attributes that take an argument (the accessor method
name)—all of the others are Boolean flags.</p>
<h2 id="the-readonly-attribute">The readonly Attribute</h2>
<p>The <code>readonly</code> attribute is an easy way to make a property
read-only. It omits the setter method and prevents assignment via dot-notation,
but the getter is unaffected. As an example, let’s change our
<code>Car</code> interface to the following. Notice how you can specify
multiple attributes by separating them with a comma.</p>
<pre><code class="cp">#import</code> <code class="l"><Foundation/Foundation.h></code><code class="cp"></code>
<code class="k">@interface</code> <code class="nc">Car</code> : <code class="nc">NSObject</code>
<code class="k">@property</code> <code class="p">(</code><code class="k">getter</code><code class="o">=</code><code class="n">isRunning</code><code class="p">,</code> <code class="k">readonly</code><code class="p">)</code> <code class="kt">BOOL</code> <code class="n">running</code><code class="p">;</code>
<code class="k">-</code> <code class="p">(</code><code class="kt">void</code><code class="p">)</code><code class="nf">startEngine</code><code class="p">;</code>
<code class="k">-</code> <code class="p">(</code><code class="kt">void</code><code class="p">)</code><code class="nf">stopEngine</code><code class="p">;</code>
<code class="k">@end</code>
</pre>
<p>Instead of letting other objects change the <code>running</code> property,
we’ll set it internally via the <code>startEngine</code> and
<code>stopEngine</code> methods. The corresponding implementation can be found
below.</p>
<pre><code class="c1">// Car.m</code>
<code class="cp">#import</code> <code class="l">"Car.h"</code><code class="cp"></code>
<code class="k">@implementation</code> <code class="nc">Car</code>
<code class="k">-</code> <code class="p">(</code><code class="kt">void</code><code class="p">)</code><code class="nf">startEngine</code> <code class="p">{</code>
<code class="n">_running</code> <code class="o">=</code> <code class="kc">YES</code><code class="p">;</code>
<code class="p">}</code>
<code class="k">-</code> <code class="p">(</code><code class="kt">void</code><code class="p">)</code><code class="nf">stopEngine</code> <code class="p">{</code>
<code class="n">_running</code> <code class="o">=</code> <code class="kc">NO</code><code class="p">;</code>
<code class="p">}</code>
<code class="k">@end</code>
</pre>
<p>Remember that <code>@property</code> also generates an instance variable for
us, which is why we can access <code>_running</code> without declaring it
anywhere (we can’t use <code>self.running</code> here because the
property is read-only). Let’s test this new <code>Car</code> class by
adding the following snippet to <code>main.m</code>.</p>
<pre><code class="n">Car</code> <code class="o">*</code><code class="n">honda</code> <code class="o">=</code> <code class="p">[[</code><code class="n">Car</code> <code class="nf">alloc</code><code class="p">]</code> <code class="nf">init</code><code class="p">];</code>
<code class="p">[</code><code class="n">honda</code> <code class="nf">startEngine</code><code class="p">];</code>
<code class="nb">NSLog</code><code class="p">(</code><code class="s">@"Running: %d"</code><code class="p">,</code> <code class="n">honda</code><code class="p">.</code><code class="n">running</code><code class="p">)</code><code class="o">;</code>
<code class="n">honda</code><code class="p">.</code><code class="n">running</code> <code class="o">=</code> <code class="kc">NO</code><code class="p">;</code> <code class="c1">// Error: read-only property</code>
</pre>
<p>Up until this point, properties have really just been convenient shortcuts
that let us avoid writing boilerplate getter and setter methods. This will not
be the case for the remaining attributes, which significantly alter the
behavior of their properties. They also only apply to properties that store
Objective-C objects (opposed to primitive C data types).</p>
<h2 id="the-nonatomic-attribute">The nonatomic Attribute</h2>
<p><strong>Atomicity</strong> has to do with how properties behave in a
threaded environment. When you have more than one thread, it’s possible
for the setter and the getter to be called at the same time. This means that
the getter/setter can be interrupted by another operation, possibly resulting
in corrupted data.</p>
<p>Atomic properties lock the underlying object to prevent this from happening,
guaranteeing that the get or set operation is working with a complete value.
However, it’s important to understand that this is only one aspect of
thread-safety—using atomic properties does not necessarily mean that your
code is thread-safe.</p>
<p>Properties declared with <code>@property</code> are atomic by default, and
this does incur some overhead. So, if you’re not in a multi-threaded
environment (or you’re implementing your own thread-safety), you’ll
want to override this behavior with the <code>nonatomic</code> attribute, like
so:</p>
<pre><code class="k">@property</code> <code class="p">(</code><code class="k">nonatomic</code><code class="p">)</code> <code class="nb">NSString</code> <code class="o">*</code><code class="n">model</code><code class="p">;</code>
</pre>
<p>There is also a small, practical caveat with atomic properties. Accessors
for atomic properties must <em>both</em> be either generated or user-defined.
Only non-atomic properties let you mix-and-match synthesized accessors with
custom ones. You can see this by removing <code>nonatomic</code> from the above
code and adding a custom getter in <code>Car.m</code>.</p>
<h2 id="memory-management">Memory Management</h2>
<p>In any OOP language, objects reside in the computer’s memory,
and—especially on mobile devices—this is a scarce resource. The
goal of a memory management system is to make sure that programs don’t
take up any more space than they need to by creating and destroying objects in
an efficient manner.</p>
<p>Many languages accomplish this through garbage collection, but Objective-C
uses a more efficient alternative called <strong>object ownership</strong>.
When you start interacting with an object, you’re said to <em>own</em>
that object, which means that it’s guaranteed to exist as long as
you’re using it. When you’re done with it, you relinquish
ownership, and—if the object has no other owners—the operating
system destroys the object and frees up the underlying memory.</p>
<figure>
<img style="max-width: 400px" src="media/properties/object-ownership.png">
<figcaption>Destroying an object with
no owners</figcaption>
</figure>
<p>With the advent of <a href="memory-management.html#automatic-reference-counting">Automatic Reference
Counting</a>, the compiler manages all of your object ownership automatically.
For the most part, this means that you’ll never to worry about how the
memory management system actually works. But, you do have to understand the
<code>strong</code>, <code>weak</code> and <code>copy</code> attributes of
<code>@property</code>, since they tell the compiler what kind of relationship
objects should have.</p>
<h3 id="the-strong-attribute">The strong Attribute</h3>
<p>The <code>strong</code> attribute creates an owning relationship to whatever
object is assigned to the property. This is the implicit behavior for all
object properties, which is a safe default because it makes sure the value
exists as long as it’s assigned to the property.</p>
<p>Let’s take a look at how this works by creating another class called
<code>Person</code>. It’s interface just declares a <code>name</code>
property:</p>
<pre><code class="c1">// Person.h</code>
<code class="cp">#import</code> <code class="l"><Foundation/Foundation.h></code><code class="cp"></code>
<code class="k">@interface</code> <code class="nc">Person</code> : <code class="nc">NSObject</code>
<code class="k">@property</code> <code class="p">(</code><code class="k">nonatomic</code><code class="p">)</code> <code class="nb">NSString</code> <code class="o">*</code><code class="n">name</code><code class="p">;</code>
<code class="k">@end</code>
</pre>
<p>The implementation is shown below. It uses the default accessors generated
by <code>@property</code>. It also overrides <code>NSObject</code>’s
<code>description</code> method, which returns the string representation of the
object.</p>
<pre><code class="c1">// Person.m</code>
<code class="cp">#import</code> <code class="l">"Person.h"</code><code class="cp"></code>
<code class="k">@implementation</code> <code class="nc">Person</code>
<code class="k">-</code> <code class="p">(</code><code class="nb">NSString</code> <code class="o">*</code><code class="p">)</code><code class="nf">description</code> <code class="p">{</code>
<code class="k">return</code> <code class="kc">self</code><code class="p">.</code><code class="n">name</code><code class="p">;</code>
<code class="p">}</code>
<code class="k">@end</code>
</pre>
<p>Next, let’s add a <code>Person</code> property to the <code>Car</code>
class. Change <code>Car.h</code> to the following.</p>
<pre><code class="c1">// Car.h</code>
<code class="cp">#import</code> <code class="l"><Foundation/Foundation.h></code><code class="cp"></code>
<code class="cp">#import</code> <code class="l">"Person.h"</code><code class="cp"></code>
<code class="k">@interface</code> <code class="nc">Car</code> : <code class="nc">NSObject</code>
<code class="k">@property</code> <code class="p">(</code><code class="k">nonatomic</code><code class="p">)</code> <code class="nb">NSString</code> <code class="o">*</code><code class="n">model</code><code class="p">;</code>
<code class="k">@property</code> <code class="p">(</code><code class="k">nonatomic</code><code class="p">,</code> <code class="k">strong</code><code class="p">)</code> <code class="n">Person</code> <code class="o">*</code><code class="n">driver</code><code class="p">;</code>
<code class="k">@end</code>
</pre>
<p>Then, consider the following iteration of <code>main.m</code>:</p>
<pre><code class="c1">// main.m</code>
<code class="cp">#import</code> <code class="l"><Foundation/Foundation.h></code><code class="cp"></code>
<code class="cp">#import</code> <code class="l">"Car.h"</code><code class="cp"></code>
<code class="cp">#import</code> <code class="l">"Person.h"</code><code class="cp"></code>
<code class="kt">int</code> <code class="nf">main</code><code class="p">(</code><code class="kt">int</code> <code class="n">argc</code><code class="p">,</code> <code class="kt">const</code> <code class="kt">char</code> <code class="o">*</code> <code class="n">argv</code><code class="p">[])</code> <code class="p">{</code>
<code class="k">@autoreleasepool</code> <code class="p">{</code>
<code class="n">Person</code> <code class="o">*</code><code class="n">john</code> <code class="o">=</code> <code class="p">[[</code><code class="n">Person</code> <code class="nf">alloc</code><code class="p">]</code> <code class="nf">init</code><code class="p">];</code>
<code class="n">john</code><code class="p">.</code><code class="n">name</code> <code class="o">=</code> <code class="s">@"John"</code><code class="p">;</code>
<code class="n">Car</code> <code class="o">*</code><code class="n">honda</code> <code class="o">=</code> <code class="p">[[</code><code class="n">Car</code> <code class="nf">alloc</code><code class="p">]</code> <code class="nf">init</code><code class="p">];</code>
<code class="n">honda</code><code class="p">.</code><code class="n">model</code> <code class="o">=</code> <code class="s">@"Honda Civic"</code><code class="p">;</code>
<code class="n">honda</code><code class="p">.</code><code class="n">driver</code> <code class="o">=</code> <code class="n">john</code><code class="p">;</code>
<code class="nb">NSLog</code><code class="p">(</code><code class="s">@"%@ is driving the %@"</code><code class="p">,</code> <code class="n">honda</code><code class="p">.</code><code class="n">driver</code><code class="p">,</code> <code class="n">honda</code><code class="p">.</code><code class="n">model</code><code class="p">);</code>
<code class="p">}</code>
<code class="k">return</code> <code class="mi">0</code><code class="p">;</code>
<code class="p">}</code>
</pre>
<p>Since <code>driver</code> is a strong relationship, the <code>honda</code>
object takes ownership of <code>john</code>. This ensures that it will be valid
as long as <code>honda</code> needs it.</p>
<h3 id="the-weak-attribute">The weak Attribute</h3>
<p>Most of the time, the <code>strong</code> attribute is intuitively what you
want for object properties. However, strong references pose a problem if, for
example, we need a reference from <code>driver</code> back to the
<code>Car</code> object he’s driving. First, let’s add a
<code>car</code> property to <code>Person.h</code>:</p>
<pre><code class="c1">// Person.h</code>
<code class="cp">#import</code> <code class="l"><Foundation/Foundation.h></code><code class="cp"></code>
<code class="k">@class</code> <code class="nc">Car</code>;
<code class="k">@interface</code> <code class="nc">Person</code> : <code class="nc">NSObject</code>
<code class="k">@property</code> <code class="p">(</code><code class="k">nonatomic</code><code class="p">)</code> <code class="nb">NSString</code> <code class="o">*</code><code class="n">name</code><code class="p">;</code>
<code class="k">@property</code> <code class="p">(</code><code class="k">nonatomic</code><code class="p">,</code> <code class="k">strong</code><code class="p">)</code> <code class="n">Car</code> <code class="o">*</code><code class="n">car</code><code class="p">;</code>
<code class="k">@end</code>
</pre>
<p>The <code>@class Car</code> line is a forward declaration of the
<code>Car</code> class. It’s like telling the compiler, “Trust me,
the <code>Car</code> class exists, so don’t try to find it right
now.” We have to do this instead of our usual <code>#import</code>
statement because <code>Car</code> also imports <code>Person.h</code>, and we
would have an endless loop of imports. (Compilers don’t like endless
loops.)</p>
<p>Next, add the following line to <code>main.m</code> right after the
<code>honda.driver</code> assignment:</p>
<pre><code class="n">honda</code><code class="p">.</code><code class="n">driver</code> <code class="o">=</code> <code class="n">john</code><code class="p">;</code>
<code class="n">john</code><code class="p">.</code><code class="n">car</code> <code class="o">=</code> <code class="n">honda</code><code class="p">;</code> <code class="c1">// Add this line</code>
</pre>
<p>We now have an owning relationship from <code>honda</code> to
<code>john</code> and another owning relationship from <code>john</code> to
<code>honda</code>. This means that both objects will <em>always</em> be owned
by another object, so the memory management system won’t be able to
destroy them even if they’re no longer needed.</p>
<figure>
<img style="max-width: 280px" src="media/properties/retain-cycle.png">
<figcaption>A retain cycle between the
<code>Car</code> and <code>Person</code> classes</figcaption>
</figure>
<p>This is called a <strong>retain cycle</strong>, which is a form of memory
leak, and memory leaks are bad. Fortunately, it’s very easy to fix this
problem—just tell one of the properties to maintain a <strong>weak
reference</strong> to the other object. In <code>Person.h</code>, change the
<code>car</code> declaration to the following:</p>
<pre><code class="k">@property</code> <code class="p">(</code><code class="k">nonatomic</code><code class="p">,</code> <code class="k">weak</code><code class="p">)</code> <code class="n">Car</code> <code class="o">*</code><code class="n">car</code><code class="p">;</code>
</pre>
<p>The <code>weak</code> attribute creates a non-owning relationship to
<code>car</code>. This allows <code>john</code> to have a reference to
<code>honda</code> while avoiding a retain cycle. But, this also means that
there is a possibility that <code>honda</code> will be destroyed while
<code>john</code> still has a reference to it. Should this happen, the
<code>weak</code> attribute will conveniently set <code>car</code> to
<code>nil</code> in order to avoid a dangling pointer.</p>
<figure>
<img style="max-width: 280px" src="media/properties/weak-reference.png">
<figcaption>A weak reference from the
<code>Person</code> class to <code>Car</code></figcaption>
</figure>
<p>A common use case for the <code>weak</code> attribute is parent-child data
structures. By convention, the parent object should maintain a strong reference
with it’s children, and the children should store a weak reference back
to the parent. Weak references are also an inherent part of the delegate design
pattern.</p>
<p>The point to take away is that two objects should never have strong
references to each other. The <code>weak</code> attribute makes it possible to
maintain a cyclical relationship without creating a retain cycle.</p>
<h3 id="the-copy-attribute">The copy Attribute</h3>
<p>The <code>copy</code> attribute is an alternative to <code>strong</code>.
Instead of taking ownership of the existing object, it creates a copy of
whatever you assign to the property, then takes ownership of that. Only objects
that conform to the <a href="https://developer.apple.com/library/ios/documentation/cocoa/Reference/Foundation/Protocols/NSCopying_Protocol/Reference/Reference.html#//apple_ref/occ/intf/NSCopying"><code>NSCopying</code>
protocol</a> can use this attribute.</p>
<p>Properties that represent values (opposed to connections or relationships)
are good candidates for copying. For example, developers usually copy
<code>NSString</code> properties instead of strongly reference them:</p>
<pre><code class="c1">// Car.h</code>
<code class="k">@property</code> <code class="p">(</code><code class="k">nonatomic</code><code class="p">,</code> <code class="k">copy</code><code class="p">)</code> <code class="nb">NSString</code> <code class="o">*</code><code class="n">model</code><code class="p">;</code>
</pre>
<p>Now, <code>Car</code> will store a brand new instance of whatever value we
assign to <code>model</code>. If you’re working with mutable values, this
has the added perk of freezing the object at whatever value it had when it was
assigned. This is demonstrated below:</p>
<pre><code class="c1">// main.m</code>
<code class="cp">#import</code> <code class="l"><Foundation/Foundation.h></code><code class="cp"></code>
<code class="cp">#import</code> <code class="l">"Car.h"</code><code class="cp"></code>
<code class="kt">int</code> <code class="nf">main</code><code class="p">(</code><code class="kt">int</code> <code class="n">argc</code><code class="p">,</code> <code class="kt">const</code> <code class="kt">char</code> <code class="o">*</code> <code class="n">argv</code><code class="p">[])</code> <code class="p">{</code>
<code class="k">@autoreleasepool</code> <code class="p">{</code>
<code class="n">Car</code> <code class="o">*</code><code class="n">honda</code> <code class="o">=</code> <code class="p">[[</code><code class="n">Car</code> <code class="nf">alloc</code><code class="p">]</code> <code class="nf">init</code><code class="p">];</code>
<code class="nb">NSMutableString</code> <code class="o">*</code><code class="n">model</code> <code class="o">=</code> <code class="p">[</code><code class="nb">NSMutableString</code> <code class="nf">stringWithString:</code><code class="s">@"Honda Civic"</code><code class="p">];</code>
<code class="n">honda</code><code class="p">.</code><code class="n">model</code> <code class="o">=</code> <code class="n">model</code><code class="p">;</code>
<code class="nb">NSLog</code><code class="p">(</code><code class="s">@"%@"</code><code class="p">,</code> <code class="n">honda</code><code class="p">.</code><code class="n">model</code><code class="p">);</code>
<code class="p">[</code><code class="n">model</code> <code class="nf">setString:</code><code class="s">@"Nissa Versa"</code><code class="p">];</code>
<code class="nb">NSLog</code><code class="p">(</code><code class="s">@"%@"</code><code class="p">,</code> <code class="n">honda</code><code class="p">.</code><code class="n">model</code><code class="p">);</code> <code class="c1">// Still "Honda Civic"</code>
<code class="p">}</code>
<code class="k">return</code> <code class="mi">0</code><code class="p">;</code>
<code class="p">}</code>
</pre>
<p><a href="data-types/nsstring.html#nsmutablestring"><code>NSMutableString</code></a>
is a subclass of <code>NSString</code> that can be edited in-place. If the
<code>model</code> property didn’t create a copy of the original
instance, we would be able to see the altered string (<code>Nissan
Versa</code>) in the second <code>NSLog()</code> output.</p>
<h2 id="other-attributes">Other Attributes</h2>
<p>The above <code>@property</code> attributes are all you should need for
modern Objective-C applications (iOS 5+), but there are a few others that
you may encounter in older libraries or documentation.</p>
<h3 id="the-retain-attribute">The retain Attribute</h3>
<p>The <code>retain</code> attribute is the <a href="memory-management.html#manual-retain-release">Manual Retain Release</a>
version of <code>strong</code>, and it has the exact same effect: claiming
ownership of assigned values. You shouldn’t use this in an Automatic
Reference Counted environment.</p>
<h3 id="the-unsafe-unretained-attribute">The unsafe_unretained Attribute</h3>
<p>Properties with the <code>unsafe_unretained</code> attribute behave similar
to <code>weak</code> properties, but they don’t automatically set their
value to <code>nil</code> if the referenced object is destroyed. The only
reason you should need to use <code>unsafe_unretained</code> is to make your
class compatible with code that doesn’t support the <code>weak</code>
property.</p>
<h3 id="the-assign-attribute">The assign Attribute</h3>
<p>The <code>assign</code> attribute doesn’t perform any kind of
memory-management call when assigning a new value to the property. This is the
default behavior for primitive data types, and it used to be a way to implement
weak references before iOS 5. Like <code>retain</code>, you
shouldn’t ever need to explicitly use this in modern applications.</p>
<h2 id="summary">Summary</h2>
<p>This module presented the entire selection of <code>@property</code>
attributes, and we hope that you’re feeling relatively comfortable
modifying the behavior of generated accessor methods. Remember that the goal of
all these attributes is to help you focus on <em>what</em> data needs to be
recorded by letting the compiler automatically determine <em>how</em>
it’s represented. They are summarized below.</p>
<table class="multiline">
<thead>
<tr>
<th>Attribute</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>getter=</code></td>
<td>Use a custom name for the getter method.</td>
</tr>
<tr>
<td><code>setter=</code></td>
<td>Use a custom name for the setter method.</td>
</tr>
<tr>
<td><code>readonly</code></td>
<td>Don’t synthesize a setter method.</td>
</tr>
<tr>
<td><code>nonatomic</code></td>
<td>Don’t guarantee the integrity of accessors in a
multi-threaded environment. This is more efficient than the default
atomic behavior.</td>
</tr>
<tr>
<td><code>strong</code></td>
<td>Create an owning relationship between the property and the assigned
value. This is the default for object properties.</td>
</tr>
<tr>
<td><code>weak</code></td>
<td>Create a non-owning relationship between the property and the
assigned value. Use this to prevent retain cycles.</td>
</tr>
<tr>
<td><code>copy</code></td>
<td>Create a copy of the assigned value instead of referencing the
existing instance.</td>
</tr>
</tbody>
</table>
<p>Now that we’ve got properties out of the way, we can take an in-depth
look at the other half of Objective-C classes: methods. We’ll explore
everything from the quirks behind their naming conventions to dynamic method
calls.</p>
<div class="divider" style="margin-top: 2em; margin-bottom: 1.3em;"></div><table class="icon-and-text advert"><tr>
<td><a href="http://rypress.com/tutorials/cocoa"><img src="media/advert-image.png" width="120px" height="165px" class="cover"></a></td>
<td><p id="advert-text">Be sure to check out <a href="http://rypress.com/tutorials/cocoa">Ry’s Cocoa Tutorial</a>. This
brand new guide is a complete walkthrough of Mac App development, and it
leverages all of the Objective-C skills that we just discussed. <a href="http://rypress.com/tutorials/cocoa">Learn more ›</a></p></td>
</tr></table>
<div id='mailing-list'>
<div class='divider' style='margin: 1.8em -22px;'></div>
<h3>Mailing List</h3>
<p>Sign up for my low-volume mailing list to find out when new content is
released. Next up is a comprehensive <a
href='https://developer.apple.com/swift/'>Swift</a> tutorial planned for late
January.</p>
<form id='mailing-list-form'
action='/secure/mailing-list/request-add' method='get'>
<label>
<div class='label'>Email Address:</div>
<div class='input'>
<input name='email'
style='width: 200px;'
type='email' />
</div>
</label>
<input id='mailing-list-button'
class='button'
style='margin-top: .5em;'
type='submit' value='Subscribe'/>
</form>
<div style='clear: both'></div>
<p class='fine-print'>You’ll only receive emails when new tutorials are
released, and your contact information will never be shared with third
parties. <a href='/secure/mailing-list/unsubscribe'>Click here</a> to
unsubscribe.</p>
</div>
<div class='divider'></div>
<footer id='footer' class='fine-print'>
<ul>
<li><a href='/licensing.php'>© 2012-2014</a></li>
<li><a href='/'>RyPress.com</a></li>
<li>
<a href='/licensing.php'>All Rights Reserved</a>
</li>
<li>
<a href='/tos.php'>Terms of Service</a>
</li>
<li>
<a href='/privacy.php'>Privacy Policy</a>
</li>
</ul>
</footer>
</div> <!-- .content -->
</div> <!-- .page -->
</body>
</html>