-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobjective_c.html
More file actions
9567 lines (7355 loc) · 437 KB
/
Copy pathobjective_c.html
File metadata and controls
9567 lines (7355 loc) · 437 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
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><body><title>Objective-C Tutorial</title>
<h1>Objective-C Tutorial</h1>
<p>Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. This is the main programming language used by Apple for the OS X and iOS operating systems and their respective APIs, Cocoa and Cocoa Touch.</p>
<p>This reference will take you through simple and practical approach while learning Objective-C Programming language.</p>
<h1>Audience</h1>
<p>This reference has been prepared for the beginners to help them understand the basic to advanced concepts related to Objective-C Programming languages.</p>
<h1>Prerequisites</h1>
<p>Before you start doing practice with various types of examples given in this reference, I'm making an assumption that you are already aware about what is a computer program and what is a computer programming language?</p>
<h1>Compile/Execute Objective-C Programs</h1>
<p>For most of the examples given in this tutorial, you will find <b>Try it</b> option to compile and execute Objective-C programs online, so just make use of it and enjoy your learning.</p>
<p>Try the following example using <b>Try it</b> option available at the top right corner of the below sample code box −</p>
<p>© Copyright 2017. All Rights Reserved.</p>
<title>Objective-C Overview</title>
<h1>Objective-C Overview</h1>
<p>Objective-C is general-purpose language that is developed on top of C Programming language by adding features of Small Talk programming language making it an object-oriented language. It is primarily used in developing iOS and Mac OS X operating systems as well as its applications.</p>
<p>Initially, Objective-C was developed by NeXT for its NeXTSTEP OS from whom it was taken over by Apple for its iOS and Mac OS X.</p>
<h2>Object-Oriented Programming</h2>
<p>Fully supports object-oriented programming, including the four pillars of object-oriented development:</p>
<p>Encapsulation</p>
<p>Data hiding</p>
<p>Inheritance</p>
<p>Polymorphism</p>
<h2>Example Code</h2>
<h2>Foundation Framework</h2>
<p>Foundation Framework provides large set of features and they are listed below.</p>
<p>It includes a list of extended datatypes like NSArray, NSDictionary, NSSet and so on. </p>
<p>It consists of a rich set of functions manipulating files, strings, etc.</p>
<p>It provides features for URL handling, utilities like date formatting, data handling, error handling, etc.</p>
<h2>Learning Objective-C</h2>
<p>The most important thing to do when learning Objective-C is to focus on concepts and not get lost in language technical details.</p>
<p>The purpose of learning a programming language is to become a better programmer; that is, to become more effective at designing and implementing new systems and at maintaining old ones.</p>
<h2>Use of Objective-C</h2>
<p>Objective-C, as mentioned earlier, is used in iOS and Mac OS X. It has large base of iOS users and largely increasing Mac OS X users. And since Apple focuses on quality first and its wonderful for those who started learning Objective-C. </p>
<p>© Copyright 2017. All Rights Reserved.</p>
<pre class="prettyprint notranslate tryit">
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSLog (@"hello world");
[pool drain];
return 0;
}
</pre>
<title>Objective-C Environment Setup</title>
<h1>Objective-C Environment Setup</h1>
<h2>Try it Option Online</h2>
<p>You really do not need to set up your own environment to start learning Objective-C programming language. Reason is very simple, we already have set up Objective-C Programming environment online, so that you can compile and execute all the available examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online.</p>
<p>Try the following example using <b>Try it</b> option available at the top right corner of the below sample code box:</p>
<p>For most of the examples given in this tutorial, you will find <b>Try it</b> option, so just make use of it and enjoy your learning.</p>
<h2>Local Environment Setup</h2>
<p>If you are still willing to set up your environment for Objective-C programming language, you need the following two softwares available on your computer, (a) Text Editor and (b) The GCC Compiler.</p>
<h2>Text Editor</h2>
<p>This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.</p>
<p>Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX.</p>
<p>The files you create with your editor are called source files and contain program source code. The source files for Objective-C programs are typically named with the extension "<b>.m</b>".</p>
<p>Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, compile it and finally execute it.</p>
<h2>The GCC Compiler</h2>
<p>The source code written in source file is the human readable source for your program. It needs to be "compiled" to turn into machine language, so that your CPU can actually execute the program as per instructions given.</p>
<p>This GCC compiler will be used to compile your source code into final executable program. I assume you have basic knowledge about a programming language compiler.</p>
<p>GCC compiler is available for free on various platforms and the procedure to set up on various platforms is explained below.</p>
<h2>Installation on UNIX/Linux</h2>
<p>The initial step is install gcc along with gcc Objective-C package. This is done by:</p>
<p>The next step is to set up package dependencies using following command:</p>
<p>In order to get full features of Objective-C, download and install GNUStep. This can be done by downloading the package from <a href="http://wwwmain.gnustep.org/resources/downloads.php?site=ftp%3A%2F%2Fftp.gnustep.org%2Fpub%2Fgnustep%2F#core/" rel="nofollow" target="_blank">http://main.gnustep.org/resources/downloads.php</a>.</p>
<p>Now, we need to switch to the downloaded folder and unpack the file by:</p>
<p>Now, we need to switch to the folder gnustep-startup that gets created using:</p>
<p>Next, we need to configure the build process:</p>
<p>Then, we can build by:</p>
<p>We need to finally set up the environment by:</p>
<p>We have a helloWorld.m Objective-C as follows:</p>
<p>Now, we can compile and run a Objective-C file say helloWorld.m by switching to folder containing the file using cd and then using the following steps:</p>
<p>We can see the following output:</p>
<h2>Installation on Mac OS</h2>
<p>If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple's web site and follow the simple installation instructions. Once you have Xcode set up, you will be able to use GNU compiler for C/C++.</p>
<p>Xcode is currently available at <a href="http://developer.apple.com/technologies/tools/" rel="nofollow" target="_blank">developer.apple.com/technologies/tools/</a>.</p>
<h2>Installation on Windows</h2>
<p>In order to run Objective-C program on windows, we need to install MinGW and GNUStep Core. Both are available at <a href="http://www.gnu.org/software/gnustep/windows/installer.html" rel="nofollow" target="_blank">http://www.gnu.org/software/gnustep/windows/installer.html</a>.</p>
<p>First, we need to install the MSYS/MinGW System package. Then, we need to install the GNUstep Core package. Both of which provide a windows installer, which is self-explanatory.</p>
<p>Then to use Objective-C and GNUstep by selecting Start -> All Programs -> GNUstep -> Shell</p>
<p>Switch to the folder containing helloWorld.m</p>
<p>We can compile the program by using:</p>
<p>We can run the program by using:</p>
<p>We get the following output:</p>
<p>© Copyright 2017. All Rights Reserved.</p>
<pre class="prettyprint notranslate tryit">
#import <Foundation/Foundation.h>
int main()
{
/* my first program in Objective-C */
NSLog(@"Hello, World! \n");
return 0;
}
</pre>
<p>For most of the examples given in this tutorial, you will find <b>Try it</b> option, so just make use of it and enjoy your learning.</p>
</blockquote>
<h2>Local Environment Setup</h2>
<p>If you are still willing to set up your environment for Objective-C programming language, you need the following two softwares available on your computer, (a) Text Editor and (b) The GCC Compiler.</p>
<h2>Text Editor</h2>
<p>This will be used to type your program. Examples of few editors include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.</p>
<p>Name and version of text editor can vary on different operating systems. For example, Notepad will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX.</p>
<p>The files you create with your editor are called source files and contain program source code. The source files for Objective-C programs are typically named with the extension "<b>.m</b>".</p>
<p>Before starting your programming, make sure you have one text editor in place and you have enough experience to write a computer program, save it in a file, compile it and finally execute it.</p>
<h2>The GCC Compiler</h2>
<p>The source code written in source file is the human readable source for your program. It needs to be "compiled" to turn into machine language, so that your CPU can actually execute the program as per instructions given.</p>
<p>This GCC compiler will be used to compile your source code into final executable program. I assume you have basic knowledge about a programming language compiler.</p>
<p>GCC compiler is available for free on various platforms and the procedure to set up on various platforms is explained below.</p>
<h2>Installation on UNIX/Linux</h2>
<p>The initial step is install gcc along with gcc Objective-C package. This is done by:</p>
<pre class="prettyprint notranslate">
$ su -
$ yum install gcc
$ yum install gcc-objc
</pre>
<p>The next step is to set up package dependencies using following command:</p>
<pre class="prettyprint notranslate">
$ yum install make libpng libpng-devel libtiff libtiff-devel libobjc libxml2 libxml2-devel libX11-devel libXt-devel libjpeg libjpeg-devel
</pre>
<p>In order to get full features of Objective-C, download and install GNUStep. This can be done by downloading the package from <a href="http://wwwmain.gnustep.org/resources/downloads.php?site=ftp%3A%2F%2Fftp.gnustep.org%2Fpub%2Fgnustep%2F#core/" rel="nofollow" target="_blank">http://main.gnustep.org/resources/downloads.php</a>.</p>
<p>Now, we need to switch to the downloaded folder and unpack the file by:</p>
<pre class="prettyprint notranslate">
$ tar xvfz gnustep-startup-<version>.tar.gz
</pre>
<p>Now, we need to switch to the folder gnustep-startup that gets created using:</p>
<pre class="prettyprint notranslate">
$ cd gnustep-startup-<version>
</pre>
<p>Next, we need to configure the build process:</p>
<pre class="prettyprint notranslate">
$ ./configure
</pre>
<p>Then, we can build by:</p>
<pre class="prettyprint notranslate">
$ make
</pre>
<p>We need to finally set up the environment by:</p>
<pre class="prettyprint notranslate">
$ . /usr/GNUstep/System/Library/Makefiles/GNUstep.sh
</pre>
<p>We have a helloWorld.m Objective-C as follows:</p>
<pre class="prettyprint notranslate">
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSLog (@"hello world");
[pool drain];
return 0;
}
</pre>
<p>Now, we can compile and run a Objective-C file say helloWorld.m by switching to folder containing the file using cd and then using the following steps:</p>
<pre class="prettyprint notranslate">
$ gcc `gnustep-config --objc-flags` -L/usr/GNUstep/Local/Library/Libraries -lgnustep-base helloWorld.m -o helloWorld
$ ./helloWorld
</pre>
<p>We can see the following output:</p>
<pre class="prettyprint notranslate">
2013-09-07 10:48:39.772 tutorialsPoint[12906] hello world
</pre>
<h2>Installation on Mac OS</h2>
<p>If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple's web site and follow the simple installation instructions. Once you have Xcode set up, you will be able to use GNU compiler for C/C++.</p>
<p>Xcode is currently available at <a href="http://developer.apple.com/technologies/tools/" rel="nofollow" target="_blank">developer.apple.com/technologies/tools/</a>.</p>
<h2>Installation on Windows</h2>
<p>In order to run Objective-C program on windows, we need to install MinGW and GNUStep Core. Both are available at <a href="http://www.gnu.org/software/gnustep/windows/installer.html" rel="nofollow" target="_blank">http://www.gnu.org/software/gnustep/windows/installer.html</a>.</p>
<p>First, we need to install the MSYS/MinGW System package. Then, we need to install the GNUstep Core package. Both of which provide a windows installer, which is self-explanatory.</p>
<p>Then to use Objective-C and GNUstep by selecting Start -> All Programs -> GNUstep -> Shell</p>
<p>Switch to the folder containing helloWorld.m</p>
<p>We can compile the program by using:</p>
<pre class="prettyprint notranslate">
$ gcc `gnustep-config --objc-flags` -L /GNUstep/System/Library/Libraries hello.m -o hello -lgnustep-base -lobjc
</pre>
<p>We can run the program by using:</p>
<pre class="prettyprint notranslate">
./hello.exe
</pre>
<p>We get the following output:</p>
<pre class="prettyprint notranslate">
2013-09-07 10:48:39.772 tutorialsPoint[1200] hello world
</pre>
<title>Objective-C Program Structure</title>
<h1>Objective-C Program Structure</h1>
<p>Before we study basic building blocks of the Objective-C programming language, let us look a bare minimum Objective-C program structure so that we can take it as a reference in upcoming chapters.</p>
<h2>Objective-C Hello World Example</h2>
<p>A Objective-C program basically consists of the following parts:</p>
<p>Preprocessor Commands</p>
<p>Interface</p>
<p>Implementation</p>
<p>Method</p>
<p>Variables</p>
<p>Statements & Expressions</p>
<p>Comments</p>
<p>Let us look at a simple code that would print the words "Hello World":</p>
<p>Let us look various parts of the above program:</p>
<p>The first line of the program <i>#import <Foundation/Foundation.h></i> is a preprocessor command, which tells a Objective-C compiler to include Foundation.h file before going to actual compilation.</p>
<p>The next line <i>@interface SampleClass:NSObject</i> shows how to create an interface. It inherits NSObject, which is the base class of all objects.</p>
<p>The next line <i>- (void)sampleMethod;</i> shows how to declare a method.</p>
<p>The next line <i>@end</i> marks the end of an interface.</p>
<p>The next line <i>@implementation SampleClass</i> shows how to implement the interface SampleClass.</p>
<p>The next line <i>- (void)sampleMethod{}</i> shows the implementation of the sampleMethod.</p>
<p>The next line <i>@end</i> marks the end of an implementation.</p>
<p>The next line <i>int main()</i> is the main function where program execution begins.</p>
<p>The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the program. So such lines are called comments in the program.</p>
<p>The next line <i>NSLog(...)</i> is another function available in Objective-C which causes the message "Hello, World!" to be displayed on the screen.</p>
<p>The next line <b>return 0;</b> terminates main()function and returns the value 0.</p>
<h2>Compile & Execute Objective-C Program:</h2>
<p>© Copyright 2017. All Rights Reserved.</p>
<pre class="prettyprint notranslate tryit">
#import <Foundation/Foundation.h>
@interface SampleClass:NSObject
- (void)sampleMethod;
@end
@implementation SampleClass
- (void)sampleMethod{
NSLog(@"Hello, World! \n");
}
@end
int main()
{
/* my first program in Objective-C */
SampleClass *sampleClass = [[SampleClass alloc]init];
[sampleClass sampleMethod];
return 0;
}
</pre>
<p>Let us look various parts of the above program:</p>
<ol class="list">
<li><p>The first line of the program <i>#import <Foundation/Foundation.h></i> is a preprocessor command, which tells a Objective-C compiler to include Foundation.h file before going to actual compilation.</p></li>
<li><p>The next line <i>@interface SampleClass:NSObject</i> shows how to create an interface. It inherits NSObject, which is the base class of all objects.</p></li>
<li><p>The next line <i>- (void)sampleMethod;</i> shows how to declare a method.</p></li>
<li><p>The next line <i>@end</i> marks the end of an interface.</p></li>
<li><p>The next line <i>@implementation SampleClass</i> shows how to implement the interface SampleClass.</p></li>
<li><p>The next line <i>- (void)sampleMethod{}</i> shows the implementation of the sampleMethod.</p></li>
<li><p>The next line <i>@end</i> marks the end of an implementation.</p></li>
<li><p>The next line <i>int main()</i> is the main function where program execution begins.</p></li>
<li><p>The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the program. So such lines are called comments in the program.</p></li>
<li><p>The next line <i>NSLog(...)</i> is another function available in Objective-C which causes the message "Hello, World!" to be displayed on the screen.</p></li>
<li><p>The next line <b>return 0;</b> terminates main()function and returns the value 0.</p></li>
</ol>
<h2>Compile & Execute Objective-C Program:</h2>
<p>Now when we compile and run the program, we will get the following result.</p
<pre class="prettyprint notranslate">
2013-09-07 22:38:27.932 demo[28001] Hello, World!
</pre>
<title>Objective-C Basic Syntax</title>
<h1>Objective-C Basic Syntax</h1>
<p>You have seen a basic structure of Objective-C program, so it will be easy to understand other basic building blocks of the Objective-C programming language.</p>
<h2>Tokens in Objective-C</h2>
<p>A Objective-C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string literal, or a symbol. For example, the following Objective-C statement consists of six tokens:</p>
<p>The individual tokens are:</p>
<h2>Semicolons ;</h2>
<p>In Objective-C program, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity.</p>
<p>For example, following are two different statements:</p>
<h2>Comments</h2>
<p>Comments are like helping text in your Objective-C program and they are ignored by the compiler. They start with /* and terminate with the characters */ as shown below:</p>
<p>You can not have comments with in comments and they do not occur within a string or character literals.</p>
<h2>Identifiers</h2>
<p>An Objective-C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9).</p>
<p>Objective-C does not allow punctuation characters such as @, $, and % within identifiers. Objective-C is a <b>case-sensitive</b> programming language. Thus, <i>Manpower</i> and <i>manpower</i> are two different identifiers in Objective-C. Here are some examples of acceptable identifiers:</p>
<h2>Keywords</h2>
<p>The following list shows few of the reserved words in Objective-C. These reserved words may not be used as constant or variable or any other identifier names.</p>
<h2>Whitespace in Objective-C</h2>
<p>A line containing only whitespace, possibly with a comment, is known as a blank line, and an Objective-C compiler totally ignores it.</p>
<p>Whitespace is the term used in Objective-C to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement:</p>
<p>There must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the following statement,</p>
<p>no whitespace characters are necessary between fruit and =, or between = and apples, although you are free to include some if you wish for readability purpose.</p>
<p>© Copyright 2017. All Rights Reserved.</p>
<pre class="prettyprint notranslate">
NSLog(@"Hello, World! \n");
</pre>
<p>The individual tokens are:</p>
<pre class="prettyprint notranslate">
NSLog
@
(
"Hello, World! \n"
)
;
</pre>
<h2>Semicolons ;</h2>
<p>In Objective-C program, the semicolon is a statement terminator. That is, each individual statement must be ended with a semicolon. It indicates the end of one logical entity.</p>
<p>For example, following are two different statements:</p>
<pre class="prettyprint notranslate">
NSLog(@"Hello, World! \n");
return 0;
</pre>
<h2>Comments</h2>
<p>Comments are like helping text in your Objective-C program and they are ignored by the compiler. They start with /* and terminate with the characters */ as shown below:</p>
<pre class="prettyprint notranslate">
/* my first program in Objective-C */
</pre>
<p>You can not have comments with in comments and they do not occur within a string or character literals.</p>
<h2>Identifiers</h2>
<p>An Objective-C identifier is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a letter A to Z or a to z or an underscore _ followed by zero or more letters, underscores, and digits (0 to 9).</p>
<p>Objective-C does not allow punctuation characters such as @, $, and % within identifiers. Objective-C is a <b>case-sensitive</b> programming language. Thus, <i>Manpower</i> and <i>manpower</i> are two different identifiers in Objective-C. Here are some examples of acceptable identifiers:</p>
<pre class="prettyprint notranslate">
mohd zara abc move_name a_123
myname50 _temp j a23b9 retVal
</pre>
<h2>Keywords</h2>
<p>The following list shows few of the reserved words in Objective-C. These reserved words may not be used as constant or variable or any other identifier names.</p>
<table class="table table-bordered">
<tr>
<td style="width:25%">auto</td>
<td style="width:25%">else</td>
<td style="width:25%">long</td>
<td style="width:25%">switch</td>
</tr>
<tr>
<td>break</td>
<td>enum</td>
<td>register</td>
<td>typedef</td>
</tr>
<tr>
<td>case</td>
<td>extern</td>
<td>return</td>
<td>union</td>
</tr>
<tr>
<td>char</td>
<td>float</td>
<td>short</td>
<td>unsigned</td>
</tr>
<tr>
<td>const</td>
<td>for</td>
<td>signed</td>
<td>void</td>
</tr>
<tr>
<td>continue</td>
<td>goto</td>
<td>sizeof</td>
<td>volatile</td>
</tr>
<tr>
<td>default</td>
<td>if</td>
<td>static</td>
<td>while</td>
</tr>
<tr>
<td>do</td>
<td>int</td>
<td>struct</td>
<td>_Packed</td>
</tr>
<tr>
<td>double</td>
<td>protocol</td>
<td>interface</td>
<td>implementation</td>
</tr>
<tr>
<td>NSObject</td>
<td>NSInteger</td>
<td>NSNumber</td>
<td>CGFloat</td>
</tr>
<tr>
<td>property</td>
<td>nonatomic;</td>
<td>retain</td>
<td>strong</td>
</tr>
<tr>
<td>weak</td>
<td>unsafe_unretained;</td>
<td>readwrite</td>
<td>readonly</td>
</tr>
</table>
<h2>Whitespace in Objective-C</h2>
<p>A line containing only whitespace, possibly with a comment, is known as a blank line, and an Objective-C compiler totally ignores it.</p>
<p>Whitespace is the term used in Objective-C to describe blanks, tabs, newline characters and comments. Whitespace separates one part of a statement from another and enables the compiler to identify where one element in a statement, such as int, ends and the next element begins. Therefore, in the following statement:</p>
<pre class="prettyprint notranslate">
int age;
</pre>
<p>There must be at least one whitespace character (usually a space) between int and age for the compiler to be able to distinguish them. On the other hand, in the following statement,</p>
<pre class="prettyprint notranslate">
fruit = apples + oranges; // get the total fruit
</pre>
<title>Objective-C Data Types</title>
<h1>Objective-C Data Types</h1>
<p>In the Objective-C programming language, data types refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.</p>
<p>The types in Objective-C can be classified as follows:</p>
<p>They are arithmetic types and consist of the two types: (a) integer types and (b) floating-point types.</p>
<p>They are again arithmetic types and they are used to define variables that can only be assigned certain discrete integer values throughout the program.</p>
<p>The type specifier <i>void</i> indicates that no value is available.</p>
<p>They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types.</p>
<p>The array types and structure types are referred to collectively as the aggregate types. The type of a function specifies the type of the function's return value. We will see basic types in the following section whereas other types will be covered in the upcoming chapters.</p>
<h2>Integer Types</h2>
<p>Following table gives you details about standard integer types with its storage sizes and value ranges:</p>
<p>To get the exact size of a type or a variable on a particular platform, you can use the <b>sizeof</b> operator. The expression <i>sizeof(type)</i> yields the storage size of the object or type in bytes. Following is an example to get the size of int type on any machine:</p>
<p>When you compile and execute the above program, it produces the following result on Linux:</p>
<h2>Floating-Point Types</h2>
<p>Following table gives you details about standard float-point types with storage sizes and value ranges and their precision:</p>
<p>The header file float.h defines macros that allow you to use these values and other details about the binary representation of real numbers in your programs. Following example will print storage space taken by a float type and its range values:</p>
<p>When you compile and execute the above program, it produces the following result on Linux:</p>
<h2>The void Type</h2>
<p>The void type specifies that no value is available. It is used in three kinds of situations:</p>
<p>There are various functions in Objective-C which do not return value or you can say they return void. A function with no return value has the return type as void. For example, <b>void exit (int status);</b></p>
<p>There are various functions in Objective-C which do not accept any parameter. A function with no parameter can accept as a void. For example, <b>int rand(void);</b></p>
<p>The void type may not be understood to you at this point, so let us proceed and we will cover these concepts in upcoming chapters.</p>
<p>© Copyright 2017. All Rights Reserved.</p>
<pre class="prettyprint notranslate tryit">
#import <Foundation/Foundation.h>
int main()
{
NSLog(@"Storage size for int : %d \n", sizeof(int));
return 0;
}
</pre>
<p>When you compile and execute the above program, it produces the following result on Linux:</p>
<pre class="prettyprint notranslate">
2013-09-07 22:21:39.155 demo[1340] Storage size for int : 4
</pre>
<h2>Floating-Point Types</h2>
<p>Following table gives you details about standard float-point types with storage sizes and value ranges and their precision:</p>
<table class="table table-bordered">
<tr>
<th>Type</th>
<th>Storage size</th>
<th>Value range</th>
<th>Precision</th>
</tr>
<tr>
<td>float</td>
<td>4 byte</td>
<td>1.2E-38 to 3.4E+38</td>
<td>6 decimal places</td>
</tr>
<tr>
<td>double</td>
<td>8 byte</td>
<td>2.3E-308 to 1.7E+308</td>
<td>15 decimal places</td>
</tr>
<tr>
<td>long double</td>
<td>10 byte</td>
<td>3.4E-4932 to 1.1E+4932</td>
<td>19 decimal places</td>
</tr>
</table>
<p>The header file float.h defines macros that allow you to use these values and other details about the binary representation of real numbers in your programs. Following example will print storage space taken by a float type and its range values:</p>
<pre class="prettyprint notranslate tryit">
#import <Foundation/Foundation.h>
int main()
{
NSLog(@"Storage size for float : %d \n", sizeof(float));
return 0;
}
</pre>
<p>When you compile and execute the above program, it produces the following result on Linux:</p>
<pre class="prettyprint notranslate">
2013-09-07 22:22:21.729 demo[3927] Storage size for float : 4
</pre>
<title>Objective-C Variables</title>
<h1>Objective-C Variables</h1>
<p>A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in Objective-C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.</p>
<p>The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either a letter or an underscore. Upper and lowercase letters are distinct because Objective-C is case-sensitive. Based on the basic types explained in previous chapter, there will be the following basic variable types:</p>
<p>Objective-C programming language also allows to define various other types of variables, which we will cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc. For this chapter, let us study only basic variable types.</p>
<h2>Variable Definition in Objective-C:</h2>
<p>A variable definition means to tell the compiler where and how much to create the storage for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows:</p>
<p>Here, <b>type</b> must be a valid Objective-C data type including char, w_char, int, float, double, bool or any user-defined object, etc., and <b>variable_list</b> may consist of one or more identifier names separated by commas. Some valid declarations are shown here:</p>
<p>The line <b>int i, j, k;</b> both declares and defines the variables i, j and k; which instructs the compiler to create variables named i, j and k of type int.</p>
<p>Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows:</p>
<p>Some examples are:</p>
<p>For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables is undefined.</p>
<h2>Variable Declaration in Objective-C:</h2>
<p>A variable declaration provides assurance to the compiler that there is one variable existing with the given type and name so that compiler proceed for further compilation without needing complete detail about the variable. A variable declaration has its meaning at the time of compilation only, compiler needs actual variable declaration at the time of linking of the program.</p>
<p>A variable declaration is useful when you are using multiple files and you define your variable in one of the files, which will be available at the time of linking of the program. You will use <b>extern</b> keyword to declare a variable at any place. Though you can declare a variable multiple times in your Objective-C program but it can be defined only once in a file, a function or a block of code.</p>
<h2>Example</h2>
<p>Try the following example, where variables have been declared at the top, but they have been defined and initialized inside the main function:</p>
<p>When the above code is compiled and executed, it produces the following result:</p>
<p>Same concept applies on function declaration where you provide a function name at the time of its declaration and its actual definition can be given anywhere else. In the following example, it's explained using C function and as you know Objective-C supports C style functions also:</p>
<h2>Lvalues and Rvalues in Objective-C:</h2>
<p>There are two kinds of expressions in Objective-C:</p>
<p><b>lvalue :</b> Expressions that refer to a memory location is called "lvalue" expression. An lvalue may appear as either the left-hand or right-hand side of an assignment.</p>
<p><b>rvalue :</b> The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment.</p>
<p>Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a valid statement:</p>
<p>But following is not a valid statement and would generate compile-time error:</p>
<p>© Copyright 2017. All Rights Reserved.</p>
<pre class="prettyprint notranslate">
type variable_list;
</pre>
<p>Here, <b>type</b> must be a valid Objective-C data type including char, w_char, int, float, double, bool or any user-defined object, etc., and <b>variable_list</b> may consist of one or more identifier names separated by commas. Some valid declarations are shown here:</p>
<pre class="prettyprint notranslate">
int i, j, k;
char c, ch;
float f, salary;
double d;
</pre>
<p>The line <b>int i, j, k;</b> both declares and defines the variables i, j and k; which instructs the compiler to create variables named i, j and k of type int.</p>
<p>Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows:</p>
<pre class="prettyprint notranslate">
type variable_name = value;
</pre>
<p>Some examples are:</p>
<pre class="prettyprint notranslate">
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.
</pre>
<p>For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables is undefined.</p>
<h2>Variable Declaration in Objective-C:</h2>
<p>A variable declaration provides assurance to the compiler that there is one variable existing with the given type and name so that compiler proceed for further compilation without needing complete detail about the variable. A variable declaration has its meaning at the time of compilation only, compiler needs actual variable declaration at the time of linking of the program.</p>
<p>A variable declaration is useful when you are using multiple files and you define your variable in one of the files, which will be available at the time of linking of the program. You will use <b>extern</b> keyword to declare a variable at any place. Though you can declare a variable multiple times in your Objective-C program but it can be defined only once in a file, a function or a block of code.</p>
<h2>Example</h2>
<p>Try the following example, where variables have been declared at the top, but they have been defined and initialized inside the main function:</p>
<pre class="prettyprint notranslate tryit">
#import <Foundation/Foundation.h>
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main ()
{
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
NSLog(@"value of c : %d \n", c);
f = 70.0/3.0;
NSLog(@"value of f : %f \n", f);
return 0;
}
</pre>
<p>When the above code is compiled and executed, it produces the following result:</p>
<pre class="prettyprint notranslate">
2013-09-07 22:43:31.695 demo[14019] value of c : 30
2013-09-07 22:43:31.695 demo[14019] value of f : 23.333334
</pre>
<p>Same concept applies on function declaration where you provide a function name at the time of its declaration and its actual definition can be given anywhere else. In the following example, it's explained using C function and as you know Objective-C supports C style functions also:</p>
<pre class="prettyprint notranslate">
// function declaration
int func();
int main()
{
// function call
int i = func();
}
// function definition
int func()
{
return 0;
}
</pre>
<h2>Lvalues and Rvalues in Objective-C:</h2>
<p>There are two kinds of expressions in Objective-C:</p>
<ol class="list">
<li><p><b>lvalue :</b> Expressions that refer to a memory location is called "lvalue" expression. An lvalue may appear as either the left-hand or right-hand side of an assignment.</p></li>
<li><p><b>rvalue :</b> The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right- but not left-hand side of an assignment.</p></li>
</ol>
<p>Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a valid statement:</p>
<pre class="prettyprint notranslate">
int g = 20;
</pre>
<p>But following is not a valid statement and would generate compile-time error:</p>
<pre class="prettyprint notranslate">
10 = 20;
</pre>
<title>Objective-C Constants</title>
<h1>Objective-C Constants</h1>
<p>The constants refer to fixed values that the program may not alter during its execution. These fixed values are also called <b>literals</b>.</p>
<p>Constants can be of any of the basic data types like <i>an integer constant, a floating constant, a character constant, or a string literal</i>. There are also enumeration constants as well.</p>
<p>The <b>constants</b> are treated just like regular variables except that their values cannot be modified after their definition.</p>
<h2>Integer literals</h2>
<p>An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.</p>
<p>An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order.</p>
<p>Here are some examples of integer literals:</p>
<p>Following are other examples of various types of Integer literals:</p>
<h2>Floating-point literals</h2>
<p>A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form.</p>
<p>While representing using decimal form, you must include the decimal point, the exponent, or both and while representing using exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E.</p>
<p>Here are some examples of floating-point literals:</p>
<h2>Character constants</h2>
<p>Character literals are enclosed in single quotes e.g., 'x' and can be stored in a simple variable of <b>char</b> type.</p>
<p>A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0'). </p>
<p>There are certain characters in C when they are proceeded by a backslash they will have special meaning and they are used to represent like newline (\n) or tab (\t). Here, you have a list of some of such escape sequence codes:</p>
<p>Following is the example to show few escape sequence characters:</p>
<p>When the above code is compiled and executed, it produces the following result:</p>
<h2>String literals</h2>
<p>String literals or constants are enclosed in double quotes "". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.</p>
<p>You can break a long line into multiple lines using string literals and separating them using whitespaces.</p>
<p>Here are some examples of string literals. All the three forms are identical strings.</p>
<h2>Defining Constants</h2>
<p>There are two simple ways in C to define constants:</p>
<p>Using <b>#define</b> preprocessor.</p>
<p>Using <b>const</b> keyword.</p>
<h2>The #define Preprocessor</h2>
<p>Following is the form to use #define preprocessor to define a constant:</p>
<p>Following example explains it in detail:</p>
<p>When the above code is compiled and executed, it produces the following result:</p>
<h2>The const Keyword</h2>
<p>You can use <b>const</b> prefix to declare constants with a specific type as follows:</p>
<p>Following example explains it in detail:</p>
<p>When the above code is compiled and executed, it produces the following result:</p>
<p>Note that it is a good programming practice to define constants in CAPITALS.</p>
<p>© Copyright 2017. All Rights Reserved.</p>
<pre class="prettyprint notranslate">
212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */
</pre>
<p>Following are other examples of various types of Integer literals:</p>
<pre class="prettyprint notranslate">
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
</pre>
<h2>Floating-point literals</h2>
<p>A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form.</p>
<p>While representing using decimal form, you must include the decimal point, the exponent, or both and while representing using exponential form, you must include the integer part, the fractional part, or both. The signed exponent is introduced by e or E.</p>
<p>Here are some examples of floating-point literals:</p>
<pre class="prettyprint notranslate">
3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
</pre>
<h2>Character constants</h2>
<p>Character literals are enclosed in single quotes e.g., 'x' and can be stored in a simple variable of <b>char</b> type.</p>
<p>A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0'). </p>
<p>There are certain characters in C when they are proceeded by a backslash they will have special meaning and they are used to represent like newline (\n) or tab (\t). Here, you have a list of some of such escape sequence codes:</p>
<table class="table table-bordered">
<tr><th style="width:20%">Escape sequence</th>
<th>Meaning</th>
</tr>
<tr><td>\\</td><td>\ character</td></tr>
<tr><td>\'</td><td> ' character</td></tr>
<tr><td>\"</td><td>" character</td></tr>
<tr><td>\?</td><td>? character</td></tr>
<tr><td>\a</td><td>Alert or bell</td></tr>
<tr><td>\b</td><td>Backspace</td></tr>
<tr><td>\f</td><td>Form feed</td></tr>
<tr><td>\n</td><td>Newline</td></tr>
<tr><td>\r</td><td>Carriage return</td></tr>
<tr><td>\t</td><td>Horizontal tab</td></tr>
<tr><td>\v</td><td>Vertical tab</td></tr>
<tr><td>\ooo</td><td>Octal number of one to three digits</td></tr>
<tr><td>\xhh . . .</td><td>Hexadecimal number of one or more digits</td></tr>
</table>
<p>Following is the example to show few escape sequence characters:</p>
<pre class="prettyprint notranslate tryit">
#import <Foundation/Foundation.h>
int main()
{
NSLog(@"Hello\tWorld\n\n");
return 0;
}
</pre>
<p>When the above code is compiled and executed, it produces the following result:</p>
<pre class="prettyprint notranslate">
2013-09-07 22:17:17.923 demo[17871] Hello World
</pre>
<h2>String literals</h2>
<p>String literals or constants are enclosed in double quotes "". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.</p>
<p>You can break a long line into multiple lines using string literals and separating them using whitespaces.</p>
<p>Here are some examples of string literals. All the three forms are identical strings.</p>
<pre class="prettyprint notranslate">
"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"
</pre>
<h2>Defining Constants</h2>
<p>There are two simple ways in C to define constants:</p>
<ol class="list">
<li><p>Using <b>#define</b> preprocessor.</p></li>
<li><p>Using <b>const</b> keyword.</p></li>
</ol>
<h2>The #define Preprocessor</h2>
<p>Following is the form to use #define preprocessor to define a constant:</p>
<pre class="prettyprint notranslate">
#define identifier value
</pre>
<p>Following example explains it in detail:</p>
<pre class="prettyprint notranslate tryit">
#import <Foundation/Foundation.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{
int area;
area = LENGTH * WIDTH;
NSLog(@"value of area : %d", area);
NSLog(@"%c", NEWLINE);
return 0;
}
</pre>
<p>When the above code is compiled and executed, it produces the following result:</p>
<pre class="prettyprint notranslate">
2013-09-07 22:18:16.637 demo[21460] value of area : 50
2013-09-07 22:18:16.638 demo[21460]
</pre>
<h2>The const Keyword</h2>
<p>You can use <b>const</b> prefix to declare constants with a specific type as follows:</p>
<pre class="prettyprint notranslate">
const type variable = value;
</pre>
<p>Following example explains it in detail:</p>
<pre class="prettyprint notranslate tryit">
#import <Foundation/Foundation.h>
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
NSLog(@"value of area : %d", area);
NSLog(@"%c", NEWLINE);
return 0;
}
</pre>
<p>When the above code is compiled and executed, it produces the following result:</p>
<pre class="prettyprint notranslate">
2013-09-07 22:19:24.780 demo[25621] value of area : 50
2013-09-07 22:19:24.781 demo[25621]
</pre>
<title>Objective-C Operators</title>
<h1>Objective-C Operators</h1>
<p>An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Objective-C language is rich in built-in operators and provides following types of operators:</p>