- Computer Programming
- Learn Python
- Python Keywords
- Python Built-in Functions
- Python Examples
- Learn C++
- C++ Examples
- Learn C
- C Examples
- Learn Java
- Java Examples
- Learn C#
- Web Development
- Learn HTML
- Learn CSS
- Learn JavaScript
- JavaScript Examples
- Learn SQL
- Learn PHP
Objective-C Tutorial
Good day there, How is everything going for you?
I hope everything is all right. 😀
My name is Edwin, and I'm here to teach you Objective-C. This Objective-C tutorial is designed for those who want to start a career in Objective-C or learn more about it.
This Objective-C tutorial was created and published for beginners. But before we begin, let's talk about Objective-C first.
Introduction to Objective-C
Objective-C is a computer programming language designed by Tom Love and Brad Cox in 1984. Since it first appeared in 1984, almost more than 38 years ago, it is a very old language. And let me tell you one important thing about Objective-C: this is the primary language for all software that is made for the Apple platform, like OS X and iOS.
Objective-C programming seems closer to the C programming language, as its syntax looks similar to C programs. However, Objective-C is an object-oriented programming language.
The source code or program file of the Objective-C language should be saved with the .m extension, for example, fresherearth.m or helloworld.m. Now that I think these details are enough, let's start coding.
How an Objective-C Program looks like?
Before we start coding in Objective-C, let me first show you what a basic Objective-C program looks like. If we talk about the simplest code or programme in any programming language, then we come to know that it is the hello world program. So let's write an Objective-C program that prints "Hello World" on the output console.
#import <Foundation/Foundation.h> int main () { NSLog (@"Hello World!"); return 0; }
In the above Objective-C program, let me explain the line-by-line code.
- The first line of code is used to include the Foundation.h header file in the program so that we can use the methods defined in it. Basically, I want to use the NSLog() method in my program to output some text to the output console, and I know this method is defined in the Foundation.h header file. Therefore, it was necessary to include this header file in the program so that the method NSLog() would execute properly without any errors.
- If you have the basics of programming languages, then I will not wonder if you know that the execution of the program begins from the main() method. As most programming languages follow this rule, execution begins with the main() method. Therefore, the second line of code is written from where the execution of the code begins. int before this method refers to the return-type; using int means this method returns an integer value, which I have written as the last statement, that is, return 0;
- After the second line of code, I used an opening curly bracket, which indicates a new block of code starts.
- And inside the curly bracket, I have written a NSLog statement, which is NSLog (@"Hello World!"); which outputs the text "Hello World!" on the output console.
- And then I have written the return statement, as the main() method is defined with int as its return type, which means any integer value we have to return. Therefore, I have written "return 0;" and then closed this block of code using the closing curly bracket. That's it
If you execute this Objective-C program, here is the exact output you will get.
Hello World!
Comments in Objective-C
Comments in any programming language are either used to debug the code or to explain some line or block of code. The comments are ignored by the compiler, which means they are not executed.
To write comments in an Objective-C program, we either use // or /* */ in this way.
// this is a comment /* this is also a comment */
The only difference between these two is that // comment is used to write a single line of comment, whereas /* comment */ is used to write a comment that spans multiple lines. That is, if we write /*, then after it, everything will be treated as a comment until you use */, the closing one. For example:
#import <Foundation/Foundation.h> int main () { NSLog (@"Hi!"); // NSLog (@"Hello!"); NSLog (@"What about you?"); /* NSLog (@"How're you?"); NSLog (@"I'm fine!"); */ NSLog (@"I'm alright, thank you."); return 0; }
The output of this C# program should exactly be:
Hi! What about you? I'm alright, thank you.
Data Types in Objective-C
Data types, either in Objective-C or in any other programming language, are used to define the type of variable in a program, which ultimately defines the space to occupy. For example: If a variable is declared to be of type int, it takes up 2 bytes of memory and can hold an integer value.
The table given below lists and briefly describes the data types in Objective-C.
Data Type | Value Range |
---|---|
char | 0 to 255 |
short | -32,768 to 32,767 |
int | -2,147,483,648 to 2,147,483,647 |
long | -2,147,483,648 to 2,147,483,647 |
float | 1.2E-38 to 3.4E+38 |
double | 2.3E-308 to 1.7E+308 |
Please note that float and double are the two types used to store floating-point values. The precision of decimal places for float type is 6, and for double type it is 15.
There is a method called sizeof() available in Objective-C that can be used to find the size of all the types listed in the above table. So what are we waiting for? Let's write the code.
#import <Foundation/Foundation.h> int main() { NSLog(@"Size of 'char' Type: %d", sizeof(char)); NSLog(@"Size of 'short' Type: %d", sizeof(short)); NSLog(@"Size of 'int' Type: %d", sizeof(int)); NSLog(@"Size of 'long' Type: %d", sizeof(long)); NSLog(@"Size of 'float' Type: %d", sizeof(float)); NSLog(@"Size of 'double' Type: %d", sizeof(double)); return 0; }
The output of this Objective-C program should be:
Size of 'char' Type: 1 Size of 'short' Type: 2 Size of 'int' Type: 4 Size of 'long' Type: 8 Size of 'float' Type: 4 Size of 'double' Type: 8
In the above example, the %d is a format specifier. If you have any idea about C programming, then you are getting it. Otherwise, let me tell you that this is basically a placeholder for the value next to it. For example, writing:
"Result = %d", x;
in the NSLog(), means that the value of x will replace %d in the above code. The %d is a format specifier used for integer values.
There are some other types, such as unsigned int, unsigned sort, long double, etc., which I have not mentioned because I don't think these will be required in your program, at least if we talk about beginners. As I already mentioned, this Objective-C tutorial is designed for beginners.
Variables in Objective-C
Variables either in Objective-C or in any other programming languages, is a name used in the program to hold some values to manipulate. While declaring variables, we need to declare their type, which specifies how much space the variable takes up in the memory along with what types of values it can store. For example, let me declare a variable, say myvar, that will store integer type data.
int myvar;
For example:
#import <Foundation/Foundation.h> int main() { int x = 10; int y = 20; int sum = x + y; NSLog(@"Sum = %d", sum); return 0; }
The output of this Objective-C program should exactly be:
Sum = 30
However the same program can also be written as:
#import <Foundation/Foundation.h> int main() { int x = 10, y = 20; NSLog(@"Sum = %d", x+y); return 0; }
which will produce the exact output as of the previous program's output.
There are certain rules you need to keep in mind while creating or naming a variable in Objective-C, which are:
A variable can be a combination of letters, digits, and underscore characters, but it must start with either A-Z, a-z, or an underscore character. For
example: mynum, my_num, myNum, my23num, mynum23_ etc. Since Objective-C is a case-sensitive language, therefore the
variable mynum is not equal to myNum.
Operators in Objective-C
This section covers the operators in Objective-C. Operators are used to perform operations within the program. For example, to add two numbers, we need to use the + operator. Here is the list of operators we are going to discuss in this section: arithmetic, relational, logical, bitwise, assignment, and some other operators which are &, *, and ?:. Let's start with arithmetic.
Objective-C Arithmetic Operators
- +
- -
- *
- /
- %
- ++
- --
For example:
#import <Foundation/Foundation.h> int main () { int x=15, y=6; NSLog(@"%d", x+y); NSLog(@"%d", x-y); NSLog(@"%d", x*y); NSLog(@"%d", x/y); NSLog(@"%d", x%y); x++; NSLog(@"%d", x); x--; NSLog(@"%d", x); return 0; }
The exact output of this Objective-C program should be:
21 9 90 2 3 16 15
The % operator returns the remainder value while dividing the first number by the second. The ++ is an increment operator used to increment the value by 1. The -- is a decrement operator used to decrement the value by 1.
Objective-C Relational Operators
- ==
- !=
- >
- <
- >=
- <=
For example:
#import <Foundation/Foundation.h> int main () { int x=15, y=6; NSLog(@"%d", x==y); NSLog(@"%d", x!=y); NSLog(@"%d", x>y); NSLog(@"%d", x<y); NSLog(@"%d", x>=y); NSLog(@"%d", x<=y); return 0; }
The output produced by this Objective-C program should exactly be.
0 1 1 0 1 0
1 indicates "true," whereas 0 indicates "false."
Objective-C Logical Operators
- &&
- ||
- !
For example:
#import <Foundation/Foundation.h> int main () { int x=1, y=0, z=1; NSLog(@"%d", x&&y); NSLog(@"%d", x&&z); NSLog(@"%d", x||y); NSLog(@"%d", !x); NSLog(@"%d", !y); return 0; }
The output of this Objective-C program should exactly be:
1 1 0 1
The && is a logical AND operator that returns true (1) if both operands are true. The || is a logical OR operator that returns true if either of the two specified operands is true. The ! is a logical NOT operator that is used to reverse the logical state, that is, if the operand is true, then it will become false, and vice-versa.
Objective-C Assignment Operators
- = assigns the value.
- += Add, then assign the value. x += 10 is same as x = x+10.
- -= subtract, then assign the value. x -= 10 is same as x = x-10.
- *= multiply, then assign the value. x *= 10 is same as x = x*10.
- /= divide, then assign the value. x /= 10 is same as x = x/10.
- %= take modulus, then assign the value. x %= 10 is same as x = x%10.
- <<= left shift, then assign the value. x <<= 10 is same as x = x<<10.
- >>= right shift, then assign the value. x >>=10 is same as x = x>>10.
- &= find bitwise AND then assign the value. x & 10 is same as x = x&10.
- ^= Find bitwise exclusive OR then assign the value. x ^=10 is same as x = x^10.
- |= find bitwise inclusive OR, assign the value. x |= 10 is same as x = x|10.
Objective-C Bitwise Operators
- & - AND
- | - OR
- ^ - XOR
- ˜ - Ones Complement
- << - Left shift
- >> - Right shift
The bitwise operator operates on bits. Here are some bitwise operations that you might be interested in.
- 1 & 1 gives 1
- 1 & 0 gives 0
- 0 & 1 gives 0
- 0 & 0 gives 0
- 1 | 1 gives 1
- 1 | 0 gives 1
- 0 | 1 gives 1
- 0 | 0 gives 0
- 0 ^ 1 gives 1
- 1 ^ 0 gives 1
- 0 ^ 0 gives 0
- 1 ^ 1 gives 0
Some other operators are &, *, and ?:. The & operator is used when we need to find the address of a variable. The * is a pointer to a variable operator. The ?: operator is called as ternary operator and is used as an alternative to the if...else statement.
Objective-C Decision Making
In this section, we will discuss decision-making statements in Objective-C. Decision-making statements are used to perform decisive tasks based on the conditions defined.
The if Statement
The if statement is used when we need to execute some block of code only when the defined condition is met. For example:
#import <Foundation/Foundation.h> int main () { int num = 14; if(num%2==0) { NSLog(@"%d is an even number.", num); } return 0; }
This Objective-C example program will produce the following output:
14 is an even number.
As you can see from the above Objective-C example, The statement NSLog() will only be executed when the condition num%2==0 evaluates to be true. Otherwise, this statement will not be executed. And since the condition, which is num%2==0 or 14%2==0 or 0==0, evaluates to be true, the NSLog statement was executed, and we have got the output that we have seen above.
Now the question is: what if the condition evaluates to be false? That is, what if we need another block of code to be executed if the specified condition is not met? Then no problem, we have another combination of statements, which is if...else 😄. Let's discuss it in the next section.
The if...else Statement
The if/else statement is used in Objective-C when we need to execute some block of code if the given condition is met, otherwise execute another block of code. For example:
#import <Foundation/Foundation.h> int main () { int num = 13; if(num%2==0) { NSLog(@"%d is an even number.", num); } else { NSLog(@"%d is an odd number.", num); } return 0; }
The output should exactly be:
13 is an odd number.
The switch Case
The switch statement is used when we need to evaluate an expression or variable, and the value that we get from the evaluated expression or variable will be matched with multiple defined cases to execute a particular block of code. For example:
#import <Foundation/Foundation.h> int main () { int week = 3; switch(week) { case 0: NSLog(@"Today is Sunday."); break; case 1: NSLog(@"Today is Monday."); break; case 2: NSLog(@"Today is Tuesday."); break; case 3: NSLog(@"Today is Wednesday."); break; case 4: NSLog(@"Today is Thursday."); break; case 5: NSLog(@"Today is Friday."); break; case 6: NSLog(@"Today is Saturday."); break; default: NSLog(@"Something went wrong!"); break; } return 0; }
In the above Objective-C program, since the value of the variable week is 3, that matches the case with value 3. Therefore, the block of code inside that case will be executed, printing the text "Today is Wednesday" on the output console.
Today is Wednesday.
The break statement is used when we need to break out of the current loop or switch.
Loops in Objective-C
A loop in Objective-C or in any other programming language is used when we need to execute some block of code a particular number of times or to continue the execution of some block of code until the defined condition continues to be met.
The while Loop
The while loop is used when we need to continue the execution of some block of code until the given condition continues to be met. The general form of the while loop in Objective-C is:
while (condition) { // block of code to // execute if // condition is true }
For example:
#import <Foundation/Foundation.h> int main () { int num = 4, i=1; while (i<=10) { NSLog(@"%d * %d = %d", num, i, num*i); i++; } return 0; }
The output produced by this Objective-C example should exactly be:
4 * 1 = 4 4 * 2 = 8 4 * 3 = 12 4 * 4 = 16 4 * 5 = 20 4 * 6 = 24 4 * 7 = 28 4 * 8 = 32 4 * 9 = 36 4 * 10 = 40
When the value of variable "i" becomes 11, then the defined condition evaluates to be false, and the execution of the block of code available inside the while loop stops.
The do...while Loop
The do...while loop does a similar job as the while loop, except that this loop allows its block of code to be executed at once even if the condition initially evaluates to be false. This is because its condition is applied after the body of the loop. The general form of the do...while loop is:
do { // block of code to be executed; } while (condition);
For example:
#import <Foundation/Foundation.h> int main () { int num = 4;; do { NSLog(@"Hello there,"); } while (num<3); return 0; }
The output of this example should exactly be:
Hello there,
The for Loop
The for loop in Objective-C does the same job, that is, it is used to execute some block of code multiple times. Here is the general form of the for loop in Objective-C.
for (initialize; condition; update) { // block of code to continue // its execution until // condition evaluates to be true }
The initialize statement executes first and only once. The condition statement executes at first and every time before entering the block of the for loop. The update statement executes every time after executing the block of code defined inside the for loop. Let me take an example:
#import <Foundation/Foundation.h> int main () { int num = 4, i; for (i=1; i<=10; i++) { NSLog(@"%d * %d = %d", num, i, num*i); } return 0; }
If you execute this Objective-C example program demonstrating the for loop, it will produce the same output as the second previous program's output (output of the while loop's program).
Arrays in Objective-C
Arrays are used when we need to store multiple values using a single variable. Here is the general form to declare an array variable in Objective-C.
type arrayName[arraySize];
For example:
int myNums[10];
declares an array variable named myNums that can hold up to 10 values. Since indexing in arrays starts with 0, therefore, myNums[0] refers to the first value or element, myNums[1] refers to the second value, and so on.
If you want to initialise values for an array variable at the time of its declaration, Then there is no need to define its size. All the values you are going to initialise in the array will be initialised without any problem. And the size of the array will be equal to the number of values you initialised for it. For example:
int myNums[] = {1, 23, 53, 10};
To access any particular value from an array, you need to use the index number of that value. For example:
#import <Foundation/Foundation.h> int main () { int myNums[] = {1, 23, 53, 10}; NSLog(@"Value at Position No.2 or Index No.1 = %d", myNums[1]); return 0; }
The output should exactly be:
Value at Position No.2 or Index No.1 = 23
myNums[0] refers to the value available in the first position.
Let me create another example on Objective-C arrays and close the discussion on it. I will not go into details, as it has already been stated that this Objective-C tutorial is for beginners. Now in the following program, I will use a for loop to initialise some random elements in an array, then use another for loop to print the elements of the array back on the output console.
#import <Foundation/Foundation.h> int main () { int x[10], num=13, multiplier=1, i; for(i=0; multiplier<=10; i++, multiplier++) { x[i] = num*multiplier; } for(i=0; i<10; i++) { NSLog(@"%d", x[i]); } return 0; }
The output should be:
13 26 39 52 65 78 91 104 117 130
That's all. I hope you like this tutorial 😏. If you want to explore more with me, then let me know through any of our social media channels, like email, Facebook, or any other. The link to our social networks can be found in the "contact us" section at the bottom of the page. Thank you, and have a good day ☺.