/
index.html
1060 lines (858 loc) · 41.5 KB
/
index.html
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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Programming with C Blocks on Apple Devices</title>
<style type="text/css" media="screen">
@import url("pwcblocks.css");
</style>
</head>
<body><div class="container">
<div style="float:right; margin-top:14px;">
<script type="text/javascript">
var flattr_url = 'http://thirdcog.eu/pwcblocks/';
</script>
<script src="http://api.flattr.com/button/load.js" type="text/javascript"></script>
</div>
<h1 style="margin-bottom:0"><a href="http://thirdcog.eu/pwcblocks/">Programming with C Blocks</a></h1>
<b> On Apple Devices</b><br />
<em>by <a href="mailto:joachimb@gmail.com">Joachim Bengtsson</a></em>
<ol class="toc">
<li><a href="#whatareblocks">What are Blocks?</a></li>
<li><a href="#whyuseblocks">What are Blocks Good For?</a></li>
<li><a href="#gettingstarted">Getting Started</a>
<ol>
<li><a href="#snowleo">On and for Mac OS X 10.6 Snow Leopard, or for iOS 4</a></li>
<li><a href="#leoiphone">On Mac OS X 10.5 Leopard or for iPhone</a></li>
</ol>
</li>
<li><a href="#cblocks">Blocks in C
<ol>
<li><a href="#cblocks-usage">Syntax and Usage</a></li>
<li><a href="#cblocks-memory">Memory Management</a></li>
</ol>
</li>
<li><a href="#objcblocks"><strong>Blocks in Objective-C</strong></li>
<li><a href="#arcblocks"><strong>Blocks and ARC (Automatic Reference Counting)</strong></li>
<li><a href="#cppblocks">Blocks in C++</a></li>
<li><a href="#goodies">Block Goodies</a></li>
<li><a href="#references">References and Additional Sources</a></li>
<li><a href="#versions">Version History and Downloads</a></li>
<li><a href="#disqus_thread">0 Comments</a></li>
</ol>
<h2><span class="headno">0</span><a name="introduction" href="#introduction">Introduction</a></h2>
<p>
In Mac OS X 10.6, Apple introduced a syntax and runtime for using blocks (more commonly known as closures)
in C and Objective-C. These were both later back-ported to Mac OS X 10.5 and the iPhone by Plausible Labs.
However, there is very little documentation on blocks; even Apple's documentation that come with 10.6
is very vague on what memory management rules apply. I hope that you can avoid all the trial-and-error
that I went through with the help of this guide.
</p>
<p>
This is sort of a bottom-up tutorial, going from the absolute basics in C, and moving towards higher
abstractions in Objective-C. I doubt that reading just the Objective-C part will do you much good;
at least, read the chapter on <a href="#cblocks-memory">memory management in C</a> first.
<p>
<p>
Have fun!<br /> <a href="http://nevyn.nu/">Joachim Bengtsson</a>
</p>
<h2><span class="headno">1</span><a name="whatareblocks" href="#whatareblocks">What are Blocks?</a></h2>
<p>
Blocks are like functions, but written inline with the rest of your code, <em>inside</em> other functions. They are also
called <a href="http://en.wikipedia.org/wiki/Closure_(computer_science)" title="Closure (computer science) - Wikipedia,
the free encyclopedia">closures</a>, because they <em>close</em> around variables in your scope. (They can also be called
lambdas). Let me demonstrate what this means:
</p>
<div class="codeblock">
<a class="codedownload" href="counter.zip">counter.zip</a>
<pre><code>#include <stdio.h>
#include <Block.h>
typedef int (^IntBlock)();
IntBlock counter(int start, int increment) {
__block int i = start;
return Block_copy( ^ {
int ret = i;
i += increment;
return ret;
});
}
int main() {
IntBlock mycounter = counter(5, 2);
printf("First call: %d\n", mycounter());
printf("Second call: %d\n", mycounter());
printf("Third call: %d\n", mycounter());
Block_release(mycounter);
return 0;
}
/* Output:
First call: 5
Second call: 7
Third call: 9
*/
</code></pre>
</div>
<p>
<code>counter</code> is an ordinary C function that returns one of these fabled <em>blocks</em>. When you have
a reference to one, you can <em>call</em> it, just as if it was a function pointer. The difference is that the
block can use the variables in <code>counter</code> <em>even after the call to that function has returned!</em>
The variables <code>i</code> and <code>increment</code> have become a part of the state of the block
<code>mycounter</code>. I will go into more detail of how each part of this example works in
<a href="#cblocks">chapter 4</a>.
</p>
<h2><span class="headno">2</span><a name="whyuseblocks" href="#whyuseblocks">What are Blocks Good For?</a></h2>
<p>
<strong>In Ruby</strong>, they are used in place of many control structures. The standard
<code>for</code> loop is replaced by an ordinary function taking a block:
</p>
<div class="codeblock">
<pre><code>
[1, 2, 3, 4].each do |i|
puts i
end
# outputs the numbers 1, 2, 3, 4 on a line each
</code></pre></div>
<p>
<code>each</code> is an ordinary function that takes a block: the block is the code between the 'do' and the
'end'. This is much more powerful than one might think, because with the ability to write your own control
structures, you no longer need to depend on the evolution of the language to make your code terse and readable.
Functional programming has many such useful control structures, such as the
<a href="http://en.wikipedia.org/wiki/Map_(higher-order_function)"title="Map (higher-order function) - Wikipedia,
the free encyclopedia"><code>map</code></a> and <a href="http://en.wikipedia.org/wiki/Reduce_(higher-order_function)"
title="Fold (higher-order function) - Wikipedia, the free encyclopedia"><code>reduce</code></a> functions; the
first maps each value in a list to another value, while the second reduces a list of values to a single value
(e g the sum of integers in the list). This is an entire topic in itself, and I encourage to learn more about
functional programming on Wikipedia as I won't be covering that anymore here.
</p>
<p>
<strong>In Erlang</strong>, they are used as a concurrency primitive together with the 'light-weight
process', instead of the thread. This simple example looks through an array looking for a match, but each element is tested
in its own separate process; each element being tested at the same time.
</p>
<div class="codeblock">
<pre><code>some_function() ->
lists:for_each([1, 2, 3, 4], fun(element) -> % (1)
spawn(fun -> % (2)
if
element > 1 andalso element < 4 -> % (3)
io:format("Found a match: ~p!~n", [element]); % (4)
true -> true
end
end
end),
io:format("This line appears after the above statement, "
"but still executes before the code in it."). % (5)
% Outputs:
% This line appears after the above statement, but still executes before the code in it.
% Found a match: 3!
% Found a match: 2!
% OR with the lines swapped in any order, depending on scheduling</code></pre></div>
<p>
Erlang looks weird to the uninitiated, so I'll step it through for you. On the line numbered (1),
we define an array with four numbers as elements, and calls the function <code>lists:for_each</code>
with that list as a first argument, and a block taking one argument as the second argument
(just as the function <code>Enumerable#each</code> takes a block argument in the Ruby example above).
The block begins at the <code>-></code> and goes on until the last <code>end</code>. All that first
block does is it <code>spawn</code>s a new Erlang process (line (2)), again taking a block as an argument
to do the actual test, but now THIS block (line (2) still) is executing concurrently, and thus the test
on line (3) is done concurrently for all elements in the array.
</p>
<p>
<strong>In Cocoa</strong>, they can be used in both these ways, and more; for example, they are
good for callbacks and delayed execution. Examples of these uses can be found at <a href="#ref4">mikeash.com [4]</a>.
Apple's main reason for introducing blocks in C is most likely because they are perfect
building blocks for concurrency. You can read more about Apple's Grand Central Dispatch in
<a href="#ref5">[5]</a>.
</p>
<h2><span class="headno">3</span><a name="gettingstarted" href="#gettingstarted">Getting Started</a></h2>
<h3><a name="snowleo" href="#snowleo">On and for Mac OS X 10.6 Snow Leopard, or for iOS 4</a></h3>
<ol>
<li>
You're done! Block support is an integral part of Snow Leopard and iOS 4 and there's
nothing you need to do to use them. Even the standard library for blocks is included
in libSystem, so you always automatically link with it.
</li>
</ol>
<!--<p class="notetoself">
TODO Okay that's true for Cocoa apps, but what about plain C apps? Non-Xcode projects?
</p>-->
<h3><a name="leoiphone" href="#leoiphone">On Mac OS X 10.5 Leopard or for iPhone</a></h3>
<p>
If you want to use blocks in applications targetting Mac OS 10.5 or iPhone OS 2 or 3,
you need to use the third-party GCC fork <a href="http://code.google.com/p/plblocks/"
title="plblocks - Project Hosting on Google Code">Plausible Blocks</a>.
<a href="http://code.google.com/p/plblocks/" title="plblocks - Project Hosting on Google Code">
From their site</a>:
<blockquote>
<p>
Plausible Blocks (PLBlocks) provides a drop-in runtime and toolchain for using blocks in iPhone 2.2+ and
Mac OS X 10.5 applications. Both the runtime and compiler patches are direct backports from Apple's Snow
Leopard source releases.
</p>
<p>
PLBlocks is provided by <a href="http://www.plausiblelabs.com/" title="Welcome to Plausible Labs">
Plausible Labs</a>.
</p>
</blockquote>
<ol>
<li>Download the latest plblocks disk image for your OS from the <a href="http://code.google.com/p/plblocks/downloads/list" title="Downloads - plblocks - Project Hosting on Google Code">Google Code page</a>.</li>
<li>Mount the disk image and run the installer. When done, keep the disk image mounted — you'll need it later.</li>
<li>Restart Xcode if it was running, and open the project in which you want to use blocks.</li>
<li>Open either the project-wide settings, or in the target settings (cmd-opt-E) for the specific target you want to use blocks in</li>
<li>Search for "Compiler"</li>
<li>From the drop-down for the setting "C/C++ Compiler Version", choose "GCC 4.2 (Plausible Blocks)" as shown in this image:<br />
<img src="http://plblocks.googlecode.com/svn/wiki/images/plblocks-select-compiler.png" />
</li>
<li>On the disk image with the plblocks installer, you'll find a folder called "PLBlocks Runtime". Save this to somewhere on your disk.</li>
<li>Now, for the target that will use blocks, you will need to link to the blocks runtime.
<ul>
<li>For an iPhone app, just drag the iPhone framework from the "Runtime" folder into your project and choose to link with your target.</li>
<li>For a Mac OS X 10.5 app, drag the Mac framework into your project and link with your target, and add an embed framework build phase. If you are unfamiliar with how to do this, <a href="http://overooped.com/post/42240519/properly-bundling-frameworks-in-your-application" title="Overooped — Properly bundling .frameworks in your application package">read my guide on framework embedding</a> (Note: You might only need to follow steps 1 through 3).</li>
</ul>
</li>
</ol>
</p>
<h2><span class="headno">4</span><a name="cblocks" href="#cblocks">Blocks in C</a></h2>
<h3><a name="cblocks-usage" href="#cblocks-usage">Syntax and Usage</a></h3>
<p>
<b>Variables pointing to blocks</b> take on the exact same syntax as variables pointing to
functions, except <code>*</code> is substituted for <code>^</code>. For example, this is a function
pointer to a function taking an int and returning a float:
</p>
<div class="codeblock"><code>float (*myfuncptr)(int);</code></div>
<p>
and this is a block pointer to a block taking an int and returning a float:
</p>
<div class="codeblock"><code>float (^myblockptr)(int);</code></div>
<p>
As with function pointers, you'll likely want to typedef those types, as it can get relatively
hairy otherwise. For example, a pointer to a block returning a block taking a block would be something
like <code>void (^(^myblockptr)(void (^)()))();</code>, which is nigh impossible to read. A simple typedef
later, and it's much simpler:
</p>
<div class="codeblock"><pre><code>typedef void (^Block)();
Block (^myblockptr)(Block);</code></pre></div>
<p>
<b>Declaring blocks</b> themselves is where we get into the unknown, as it doesn't really look like C,
although they resemble function declarations. Let's start with the basics:
</p>
<div class="codeblock"><pre><code>myvar1 = ^ returntype (type arg1, type arg2, and so on) {
block contents;
like in a function;
return returnvalue;
};</code></pre></div>
<p>
This defines a <em>block literal</em> (from after <code>=</code> to and including <code>}</code>),
explicitly mentions its return type, an argument list, the block body, a return statement, and
assigns this literal to the variable myvar1.
</p>
<p>
A <em>literal</em> is a value that can be built at compile-time. An integer literal (The
<code>3</code> in <code>int a = 3;</code>) and a string literal (The <code>"foobar"</code> in
<code>const char *b = "foobar";</code>) are other examples of literals. The fact that a block
declaration is a literal is important later when we get into memory management.
</p>
<p>
Finding a return statement in a block like this is vexing to some. Does it return from
the enclosing function, you may ask? No, it returns a value that can be used by the caller
of the block. See 'Calling blocks'. Note: If the block has multiple return statements,
they must return the same type.
</p>
<p>
Finally, some parts of a block declaration are optional. These are:
<ul>
<li>
The argument list. If the block takes no arguments, the argument list can be skipped entirely. Examples:
<div class="codeblock"><pre><code>myblock1 = ^ int (void) { return 3; }; // may be written as:
myblock2 = ^ int { return 3; }
</code></pre></div>
</li>
<li>
The return type. If the block has no return statement, void is assumed. If the block has a return
statement, the return type is inferred from it. This means you can almost always just skip the
return type from the declaration, except in cases where it might be ambiguous. Examples:
<div class="codeblock"><pre><code>myblock3 = ^ void { printf("Hello.\n"); }; // may be written as:
myblock4 = ^ { printf("Hello.\n"); };
// Both succeed ONLY if myblock5 and myblock6 are of type int(^)(void)
myblock5 = ^ int { return 3; }; // can be written as:
myblock6 = ^ { return 3; };
</code></pre></div>
</li>
</ul>
</p>
<p>
<b>Calling blocks and returning values</b> is as easy with a function or a function pointer. If you take the
value from calling the block, you will get the value returned with <code>return</code>. Example:
</p>
<div class="codeblock"><pre><code>typedef int(^IntBlock)();
IntBlock threeBlock = ^ {
return 3;
};
int three = threeBlock();
// Return values work just as in C functions. return needs to be explicit! This is not Ruby.
IntBlock fourBlock = ^ {
4;
};
// Yields on compile:
// error: incompatible block pointer types initializing 'void (^)(void)', expected 'IntBlock'
// This is because we neither specified the return type,
// nor provided a return statement, thus implying void return.
</code></pre></div>
<p>
<b>Using variables in the closure scope</b> is very straight-forward if you're just reading them. Just use them,
and they will be magically managed by your block. However, if you want to be able to modify the variable, it need to be
prefixed by the <code>__block</code> storage qualifier. Let's make the counter from the first example go forwards AND
backwards:
</p>
<div class="codeblock">
<a class="codedownload" href="counter2.zip">counter2.zip</a>
<pre><code>#include <stdio.h>
#include <Block.h>
typedef int (^IntBlock)();
typedef struct {
IntBlock forward;
IntBlock backward;
} Counter;
Counter MakeCounter(int start, int increment) {
Counter counter;
__block int i = start;
counter.forward = Block_copy( ^ {
i += increment;
return i;
});
counter.backward = Block_copy( ^ {
i -= increment;
return i;
});
return counter;
}
int main() {
Counter counter = MakeCounter(5, 2);
printf("Forward one: %d\n", counter.forward());
printf("Forward one more: %d\n", counter.forward());
printf("Backward one: %d\n", counter.backward());
Block_release(counter.forward);
Block_release(counter.backward);
return 0;
}
/* Outputs:
Forward one: 7
Forward one more: 9
Backward one: 7
*/
</code></pre></div>
<p>
Note how we in the blocks use increment without doing any work, yet reference it outside the MakeCounter function.
However, we only <em>read</em> from it. We also use <code>i</code>, but we modify it from inside the blocks. Thus,
we need the <code>__block</code> keyword with that variable.
</p>
<p>
<b>Sending and taking blocks as arguments</b> is again like doing so with function pointers. The difference is that
you can define your block inline, in the call.
</p>
<div class="codeblock">
<a class="codedownload" href="blockarguments.zip">blockarguments.zip</a>
<pre><code>#include <stdio.h>
#include <Block.h>
void intforeach(int *array, unsigned count, void(^callback)(int))
{
for(unsigned i = 0; i < count; i++)
callback(array[i]);
}
int main (int argc, const char * argv[]) {
int numbers[] = {72, 101, 108, 108, 111, 33};
intforeach(numbers, 6, ^ (int number) {
printf("%c", number);
});
printf("\n");
return 0;
}
/* Outputs:
Hello!
*/</code></pre></div>
<p>Notice how we call intforeach with an inline block. (If you're wondering about the numbers: they are the ascii codes for the letters in the word "Hello!"), and how intforeach could have been an ordinary C function taking a function pointer and still be written the exact same way except for switching the <code>^</code> for a <code>*</code>.
<h3><a name="cblocks-memory" href="#cblocks-memory">Memory Management</a></h3>
<p>
What does 'memory management' in the context of blocks mean? It doesn't mean storage for the actual code.
The code of the block is compiled and loaded into the binary like any other function. The memory a block
requires is that of the variables it has closed around; that is, any variables the block references need
to be copied into the block's private memory.
</p>
<p>
So far, we have just assumed that the memory has somehow magically become part of the block,
and will magically disappear. Unfortunately Apple haven't added a garbage collector to C,
so that's not quite the case. However, to understand the following, you must have a basic
understanding of <a href="http://en.wikipedia.org/wiki/Stack-based_memory_allocation"
title="Stack-based memory allocation - Wikipedia, the free encyclopedia">stack</a>
and <a href="http://en.wikipedia.org/wiki/Dynamic_memory_allocation"
title="Dynamic memory allocation - Wikipedia, the free encyclopedia">heap</a> memory,
and how they differ.
</p>
<p>
When you define a <em>block literal</em>, you create the storage for this literal <em>on the stack</em>.
The variable pointing to this literal can still be considered a pointer, however. This means that
the following code compiles, but does not work:
</p>
<div class="codeblock"><pre><code>typedef void(^Block)(void);
Block blockMaker() {
int a = 3; // (1)
Block block = ^ { // (2)
return a;
}
return block; // (3)
}
int main() {
Block block2 = blockMaker(); // (4)
int b = block2(); // (5)
return 0;
}
</code></pre></div>
<p>
This is basically what the code above does:
</p>
<div class="codeblock"><pre><code>Block blockMaker() {
int a = 3; // (1)
struct Block_literal_1 *block;
struct Block_literal_1 blockStorage = ...; // (2)
block = &blockStorage; // (2b)
return block; // (3)
}</code></pre></div>
<p>
At (1), the value <code>3</code> is allocated on the stack and named <code>a</code>, as expected.
At (2) and the following block, the value of <code>a</code> is copied into the block literal. Then,
also at (2) (2b in the second example), a pointer to the literal is in turn assigned to the variable <code>block</code>.
If you think of Block as just a pointer type, and the assignment in (2) as taking the address of a literal,
you might see why (3) is invalid, but we'll get to that.
</p>
<p>
In (4), the variable <code>block2</code> gets a reference to the literal in (2). However, both
the variables <code>a</code> and <code>block</code> (together with <code>block</code>s copy of
the value in <code>a</code>) have now fallen off the stack, as
<code>blockMaker</code> has returned. When we call <code>block2</code> in (5), we might
segfault, get a corrupted value, or whatever — the behavior is undefined.
</p>
<p>
The same effect can be demonstrated without involving blocks:
</p>
<div class="codeblock"><pre><code>int * intMaker() {
int a = 3; // (1)
return &a; // (2)
}
int main() {
int *b = intMaker(); // (3)
return 0;
}</code></pre></div>
<p>
<code>intMaker</code> returns a pointer to an object on the stack (1), which will disappear together with the
rest of the state of the function call when <code>intMaker</code> returns (2).
</p>
<p><a name="Block_copy"></a>
How do work around this problem? Simple — we move the block to the <em>heap</em>. The function
<code>Block_copy()</code> takes a block pointer, and if it's a stack block, copies it to the
heap, or if it's already a heap block, increases its retain count (like an immutable object
in Cocoa would do). Exactly what happens is an implementation detail, but the thing to
take away is that you should never return a block literal from a function, but rather
a copy of it.
</p>
<p><a name="Block_release"></a>
When we're done with the block, just release it with <code>Block_release()</code>. Thus,
the correct way to implement the blockMaker example is like so:
</p>
<div class="codeblock"><pre><code>typedef void(^Block)(void);
Block blockMaker() {
int a = 3;
Block block = ^ {
return a;
}
return Block_copy(block); // (1)
}
int main() {
Block block2 = blockMaker();
int b = block2();
Block_release(block2); // (2)
return 0;
}
</code></pre></div>
<p>
Notice how we move the block to the heap in (1), and discard the block when we're done with it in (2).
For anyone who has done Cocoa or CoreFoundation programming, this pattern should be familiar.
</p>
<p>
(An aside: If you try to return a literal like so: <code>Block foo() { int i = 3; return ^ { printf("Fail %d", i); }; }</code>,
the compiler will complain that you are trying to return a stack literal, which isn't possible.)
</p>
<p>
Be careful! You don't have to return from a function for something to fall
off the stack. The following example is equally invalid (<a href="#ref4">[2]</a> and <a href="#ref4">[4]</a>):
</p>
<div class="codeblock"><pre><code>typedef void(^BasicBlock)(void);
void someFunction() {
BasicBlock block;
if(condition) {
block = ^ { ... };
} else {
block = ^ { ... };
}
...
}
// Basically equivalent of:
void someFunction() {
BasicBlock block;
if(condition) {
struct Block_literal_1 blockStorage = ...;
block = &blockStorage;
} // blockStorage falls off the stack here
else
{
struct Block_literal_1 blockStorage = ...;
block = &blockStorage;
} // blockStorage falls off the stack here
// and block thus points to non-existing/invalid memory
...
}
// Correct:
void someFunction() {
BasicBlock block;
if(condition) {
block = Block_copy(^ { ... });
} else {
block = Block_copy(^ { ... });
}
...
}
</code></pre></div>
<h2><span class="headno">5</span><a name="objcblocks" href="#objcblocks">Blocks in Objective-C</a></h2>
<p>
The really weird and wonderful thing about blocks is that <strong>blocks are actually Objective-C objects</strong>.
Even if you create them from a C++ library, the specification says that every block must
have the memory layout of an Objective-C object. The runtime then adds Objective-C methods
to them, which allow them to be stored in collections, used with properties, and just generally
<em>work</em> wherever you'd expect. These methods are:
<ul>
<li>
<code>-[Block copy]</code>: Exactly the same as <a href="#Block_copy"><code>Block_copy()</code></a>. This will give you a block
on the heap with an owning reference, just like calling <code>-[NSObject copy]</code> on any other
object.
</li>
<li>
<code>-[Block retain]</code>: This one is a bit weird, and almost the single reason why
I wrote this entire guide. This calls Block_retain(). However, the conventions for Objective-C
objects say that retain MUST return the same instance that it was called with. This means
that retain cannot call copy; I'll get to why this is really, really annoying.
</li>
<li>
<code>-[Block release]</code>: <a href="#Block_release"><code>Block_release()</code></a>.
</li>
<li>
<code>-[Block autorelease]</code>: That's right, <b>blocks can be autoreleased</b>!
</li>
<li>
… And blocks inherit from NSObject, so whatever is defined on it (including your categories!) <a href="#ref3">[4]</a>
</li>
</ul>
</p>
<p>
Blocks in Objective-C have one more very important difference from blocks in C in handling
variables that reference objects. All local objects are <strong>automatically retained as they
are referenced!</strong> If you reference an instance variable from a block declared in a method,
this retains self, as you're implicitly doing <code>self->theIvar</code>. An example is in order:
</p>
<div class="codeblock">
<a class="codedownload" href="logmessage.zip">logmessage.zip</a>
<pre><code>typedef void(^BasicBlock)(void);
@interface LogMessage : NSObject {
NSString *logLevel;
}
@end
@implementation LogMessage
-(BasicBlock)printLater:(NSString*)someObject;
{
return [[^ {
NSLog(@"%@: %@",
logLevel, // (1)
someObject // (2)
);
} copy] autorelease]; // (3)
}
@end
</code></pre></div>
<p>
Here's a method that simply returns a block that lets you print the given string, prefixed by the object's log level.
In (3), the block is copied, because <a href="#cblocks-memory">as you remember</a>, you can't return a block literal since it's on the stack.
Still, we want to follow common Cocoa patterns and never return an owning reference from a method called neither
<code>copy</code>, <code>retain</code> nor <code>alloc</code>. This gives us the idiom <code>[[^{} copy] autorelease]</code>,
which is what you should always use when returning blocks.
</p>
<p>
Now, for the auto retaining magic, notice how we reference the argument object <code>someObject</code>
in (2), and implicitly <code>self</code> in (1) (which really says <code>self->logLevel</code>).
When the block is copied in (3), Block_copy notices that logLevel and someObject are objects,
and retains them. When the block is released, it will free all its captured variables,
and if they are objects, release them.
</p>
<p>
With even <code>self</code> being retained, this is a very easy way to accidentally create
reference cycles and thus memory leaks. What if you want to avoid this behavior? Just give the variable
<code>__block</code> storage (Thanks to mikeash<a href="#ref3">[4]</a> for pointing this out). Example:
</p>
<div class="codeblock">
<a class="codedownload" href="__blockself.zip">__blockself.zip</a>
<pre><code>-(void)someMethod;
{
__block TypeOfSelf *blockSelf = self;
^ {
// Because blockSelf is __block, the following reference
// won't retain self:
blockSelf->myIvar += 3;
}
...
}</code></pre></div>
<p>
Why does this work? Well, if the variable is __block, it can be changed from within a block.
If it's an object pointer, this means <em>changing the object pointer itself, not the object</em>.
If the block autoretains object pointers, what should happen if the pointer is changed,
pointing to another object? The concept is so hairy that they chose the simplest solution:
__block storage objects simply aren't autoretained.
</p>
<p>
Finally, one more memory management gotcha before we move onto syntax. Remember that blocks are objects?
And objects are automatically retained? Yes, that's right, blocks also automatically retain
blocks they refer to! (<a href="http://nopaste.me/4308" title="Objective C nopaste.me">My research</a>.)
This means that the following code will work fine:
</p>
<div class="codeblock">
<pre><code>typedef void(^BasicBlock)(void);
// Returns a block that aborts the process
-(BasicBlock)doSomethingAsynchronous;
{
BasicBlock cleanup = [[^{
// Do some common cleanup needed in all cases
} copy] autorelease];
__block AsyncDownloader *downloader = [AsyncDownloader fetch:@"http://domain/some.file" options:$dict(
@"success", [[^ {
[downloader.dataValue writeToFile:@"some/path" atomically:NO];
DisplayAlert(@"Download complete");
cleanup();
} copy] autorelease],
@"failure", [[^ {
DisplayAlert(@"Error: %@", downloader.error);
cleanup();
} copy] autorelease]
)];
return [[^ {
[downloader abort];
cleanup();
} copy] autorelease];
}</code></pre></div>
<p>
Notice how <code>downloader</code> is declared <code>__block</code> — otherwise me referencing it
in the callback blocks would retain it, and the downloader retains the blocks, thus creating a cycle.
<a href="https://bitbucket.org/snej/myutilities/src/tip/CollectionUtils.h">$dict is a very handy macro</a>
which creates a dictionary from key-value pairs (the NSDictionary constructor is too verbose for my taste).
</p>
<p>
Notice how all three blocks reference the cleanup block: it is thus retained and properly memory managed
until the referring blocks disappear.
</p>
<p><a name="blocks_in_collections"></a>
This example also highlights a problem with stack block literals — collections, such as NSDictionary above,
<code>retain</code>s its values, but <code>-[Block retain]</code> doesn't do anything on stack blocks!
Thus, we must move the blocks to the heap before we can insert them into the dictionary. For example, to
insert a few delayed actions into an array, you'd do it like this:
</p>
<div class="codeblock">
<a class="codedownload" href="arrayofblocks.zip">arrayofblocks.zip</a>
<pre><code>NSArray *someActions = [NSArray arrayWithObjects:
[[^ { NSLog(@"Hello"); } copy] autorelease],
[[^ { NSLog(@"World!"); } copy] autorelease],
[[^ { NSLog(@"Awesome.");} copy] autorelease],
nil
];
for (void(^block)() in someActions) {
block();
}
/* Outputs:
2009-08-23 13:06:06.514 arrayofblocks[32449:a0f] Hello
2009-08-23 13:06:06.517 arrayofblocks[32449:a0f] World!
2009-08-23 13:06:06.517 arrayofblocks[32449:a0f] Awesome.
*/</code>
</pre></div>
<p>
In the syntax department, you might have two questions. How do I use non-typedef'd blocks as method arguments,
and can I use them as properties? This example should make that clear:
</p>
<div class="codeblock">
<a class="codedownload" href="propertyblocks.zip">propertyblocks.zip</a>
<pre><code>#import <Foundation/Foundation.h>
#import <stdlib.h>
@interface PredicateRunner : NSObject
{
BOOL (^predicate)();
}
@property (copy) BOOL (^predicate)();
-(void)callTrueBlock:(void(^)())true_ falseBlock:(void(^)())false_;
@end
@implementation PredicateRunner
@synthesize predicate;
-(void)callTrueBlock:(void(^)())true_ falseBlock:(void(^)())false_;
{
if(predicate())
true_();
else
false_();
}
-(void)dealloc;
{
self.predicate = nil;
[super dealloc];
}
@end
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
srandom(time(NULL));
PredicateRunner *pr = [[PredicateRunner new] autorelease];
pr.predicate = ^ BOOL {
return random()%2;
};
[pr callTrueBlock:^ {NSLog(@"Yeah");} falseBlock:^ {NSLog(@"Nope");} ];
[pool drain];
return 0;
}</code></pre></div>
<p>
Typedefs will make that much easier to read, though.
</p>
<h2><span class="headno">6</span><a name="arcblocks" href="#arcblocks">Blocks and ARC (Automatic Reference Counting)</a></h2>
<p><a href="#ref0">Mike Ash has an excellent run-down of block usage with ARC[0]</a>. In summary:
<ul>
<li>
ARC can manage blocks since they are ObjC objects, but it also knows that blocks must be copied, not just retained. This
will only work however, as long as you use block types in your signatures, and not just 'id'.
</li>
<li>
__block changes meaning: it no longer means "this variable is not auto-retained by blocks", since the ObjC compiler now has the
power to do reference counting on its own. So, all the code you've written that uses <code>__block __typeof(self) selff = self</code>
should be changed to <code>__weak __typeof(self) selff = self</code> or you'll *still* be creating retain loops.
</li>
</ul>
<h2><span class="headno">7</span><a name="cppblocks" href="#cppblocks">Blocks in C++</a></h2>
<p>See <a href="#ref1">[1]</a> and <a href="#ref1">[2]</a> for details on how blocks work with C++ variables. In essence: Copy constructors and destructors are being called as expected. Read-only variables are const-copied into the block.</p>
<h2><span class="headno">8</span><a name="goodies" href="#goodies">Block Goodies</a></h2>
<p>
Code snippets, libraries and frameworks using blocks to simplify working with Objective-C
are popping up here and there as Mac and iPhone developers are figuring Blocks out
and applying them to their common tasks. I'll add them here as I find them.
<a href="#comments">Post in the comments</a> if there's something I'm missing!
</p>
<ul>
<li>
<a href="http://toxicsoftware.com/" title="toxicsoftware.com">Jonathan Wight</a> was inspired by
<a href="http://www.mikeash.com/?page=pyblog/key-value-observing-done-right.html"
title="mikeash.com: Key-Value Observing Done Right">Mike Ash's KVO Done Right</a>, and wrote a
<a href="http://toxicsoftware.com/kvoblocks/">KVO notification center based on blocks</a>
(<a href="https://bitbucket.org/schwa/kvoblocknotificationcenter/">repository</a>,
<a href="http://www.flickr.com/photos/jwight/3826876252/?likes_hd=1"
title="KVO Blocks In Action on Flickr - Photo Sharing!">demo video</a>).
A subscription now looks like this:
<div class="codeblock">
<pre><code>void *theBlock = ^(NSString *keyPath, CALayer *self, NSDictionary *change, id identifier) {
self.position = CGPointMake(self.viewPoint.scale * self.modelObject.position.x,
self.viewPoint.scale * self.modelObject.position.y);
};
CALayer *theLayer = ...;
[theLayer addKVOBlock:theBlock forKeyPath:@"modelObject.position" options:0 identifier:@"KVO_IDENTIFIER_1"];
</code></pre></div>
</li>
<li>
<a href="http://andymatuschak.org/" title="andymatuschak.org">Andy Matuschak</a> also got fed up with the
verbosity of KVO and devised
<a href="http://blog.andymatuschak.org/post/156229939/kvo-blocks-block-callbacks-for-cocoa-observers"
title="Square Signals : KVO+Blocks: Block Callbacks for Cocoa Observers">his own similar solution</a>.
Demo:
<div class="codeblock">
<pre><code>- (void)registerObservation
{
[observee addObserverForKeyPath:@"someValue"
task:^(id obj, NSDictionary *change) {
NSLog(@"someValue changed: %@", change);
}];
}</code></pre></div>
</li>
<li>
<a href="http://mogeneration.com/">MoGeneration</a> are working to make
<a href="http://github.com/mogeneration/functionalkit/tree/blocks">FunctionalKit</a> use blocks.
FunctionalKit gives you the standard map, reduce and such, but also works to make
your code more succinct and functional. There's a blog entry on
<a href="http://adams.id.au/blog/2009/04/simplifying-json-parsing-using-functionalkit/"
title="Simplifying JSON Parsing Using FunctionalKit at nosewheelie">
simplifying JSON parsing with FunctionalKit</a> over at adams.id.au, which will give
you the basic idea, even though it was written before blocks.
</li>
<li>
<a href="http://twitter.com/daagaak">Matt Wright</a> is reimplementing
<a href="http://en.wikipedia.org/wiki/Grand_Central_Dispatch">Grand Central Dispatch</a>
for Mac OS X 10.5 and the iPhone (backporting the feature from 10.6, in the same vein as PLBlocks).
His port is called <a href="http://daagaak.github.com/WiganWallgate/">Wigan Wallgate, and is
available on Github.</a>
</li>
<li>
<a href="http://www.mikeash.com/">Mike Ash</a> has an amazing repository of blocks related
articles and code, but the most impressive one is his code to use blocks in place of simple callback
function pointers. Do check out <a href="http://www.mikeash.com/pyblog/friday-qa-2011-05-06-a-tour-of-mablockclosure.html">
MABlockClosure</a>.
</ul>
<h2><span class="headno">9</span><a name="references" href="#references">References and Additional Sources</a></h2>
<p>
If you want to read more about blocks, the following links are great places to keep
reading:
</p>