Objective C Tutorial (Programing Language)
By: Luis A. Sierra


Introduction

Objective-C is a high-level general-purpose, object-oriented programming language that adds Smalltalk-style message passing (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.

What is Objetive-C


Objective-C is a high-level general-purpose, object-oriented programming language that adds Smalltalk-style message passing (messaging) to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTSTEP operating system. Due to Apple macOS’s direct lineage from NeXTSTEP, Objective-C was the standard language used, supported, and promoted by Apple for developing macOS and iOS applications (via their respective application programming interfaces (APIs), Cocoa and Cocoa Touch) from 1997, when Apple purchased NeXT until the introduction of the Swift language in 2014.

Objective-C programs developed for non-Apple operating systems or that are not dependent on Apple's APIs may also be compiled for any platform supported by GNU GNU Compiler Collection (GCC) or LLVM/Clang.

Objective-C is a thin layer atop C and is a "strict superset" of C, meaning that it is possible to compile any C program with an Objective-C compiler and to freely include C language code within an Objective-C class.

Objective-C derives its object syntax from Smalltalk. All of the syntax for non-object-oriented operations (including primitive variables, pre-processing, expressions, function declarations, and function calls) are identical to those of C, while the syntax for object-oriented features is an implementation of Smalltalk-style messaging.

Object-Oriented Programming

Objective-C fully supports object-oriented programming, including the four pillars of object-oriented development
  • Encapsulation
  • Data hiding
  • Inheritance
  • Polymorphism
The Objective-C model of object-oriented programming is based on message passing to object instances. In Objective-C, one does not call a method; one sends a message. This is unlike the Simula-style programming model used by C++. The difference between these two concepts is in how the code referenced by the method or message name is executed. In a Simula-style language, the method name is—in most cases—bound to a section of code in the target class by the compiler.

Foundation Framework

Foundation Framework
provides large set of features and they are listed below.
  • It includes a list of extended datatypes like NSArray, NSDictionary, NSSet and so on.
  • It consists of a rich set of functions manipulating files, strings, etc.
  • It provides features for URL handling, utilities like date formatting, data handling, error handling, etc.

IDEs


XCode is Apple’s IDE that developers can use to build codes for iPhones, iPad and other device-based applications. You can use the IDE to develop code using Swift programming language. It also extends support for multiple programming languages, which makes it the most superior programming language.


This intelligent integrated development environment was created to support Objective-C and Swift programming languages. It comes with modern libraries and support for modernized coding that enables swift solutions.



This is one of the best and most popular Swift IDEs you can use to build iOS applications. CodeRunner is devised only for iOS, so it doesn’t extend cross-platform support.

This is an intelligent and cross-platform IDE developed by JetBrains to help program applications using Swift language. It does offer a debugger and a powerful editor that helps build the code. You can use several analysis tools for the best outcomes and quick coding decisions.

Objective-C Get Started

Installing Xcode and Simulators

iOS, iPadOS, and (on a Mac with Apple silicon) visionOS simulators are available in macOS as part of Xcode, which is free in the Mac App Store.

To get started using Simulators:

Install Xcode from the Mac App Store.

Once installed, launch Xcode so that it can complete its first launch.

A dialog will be presented that indicates which Simulator runtimes are built-in, and which Simulator runtimes you may download. For now, choose Continue to finish setting up Xcode.

Hello World application

Hello, World! It is the first basic program in any programming language. Let's write the first program in the Objective-C programming language.

1 - Open Xcode and select Create a new Xcode project in Xcode: 


2 - Now select macOS -> Command Line Tool and click on Button Next in Xcode:


3 - Now in Product Name enter the name "HelloWorld" and choose Objective-C in Language and Click on Next Button  in Xcode:


4 - Now choose a  folder to save he project and Click on Create Button  in Xcode:


5 - Now enter the code below:

#import <Foundation/Foundation.h>


int main(int argc, const char * argv[]) {

        

    printf("Hello, World! \n");

            

    return 0;

}


6 - Now go to toolbar -> Play in Xcode: 



7 - After that you will see de result: 



For non-macOS users ðŸ˜Ž 


Code: 

#import <Foundation/Foundation.h>


int main(int argc, const char * argv[]) {

        

    printf("Hello, World! \n");

            

    return 0;

}


You can test your code here: ðŸ‘‰ https://www.jdoodle.com/execute-objective-c-online


Objective-C Comments

Comments can be used to explain Objective-C code, and to make it more readable. It can also be used to prevent execution when testing alternative code.

Single-line comments starts with two forward slashes (//).

// This is a comment
printf("Welcome to http://interesting-homemade-projects \n");

Multi-line comments start with  /* and ends with */.

/* The code below will print the url of my web site
to the screen */

printf("Welcome to http://interesting-homemade-projects \n");

Objective-C Variables

Variables are the "place" where we can store the data that the program needs.

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

data type name;

Example:

    int  Thousand = 1000;

    float Pi = 3.14;

    NSString *AuthorName = @"Luis A. Sierra";





Example 2: Mixed With C/C++


    int  Thousand = 1000;

    float Pi = 3.14;

    char AuthorName[] = "Luis A. Sierra";  // C/C++ String




Now you can see with your own eyes that the theory described above is possible. If you know C/C++, you can program in Objective-C on your own.

If you want to learn C/C++ you can see my other tutorial about C/C++:

https://interesting-homemade-projects.blogspot.com/2024/02/tutorial-cc-part-1.html



Case Sensitivity

Case sensitivity defines whether uppercase and lowercase letters are treated as distinct or equivalent.

"Objective-C : is case sensitive"



Objective-C Data Type

The following table shows the available data types in Objective-C programming language with memory size and range of values.

The table below show data type available for Objective-C:



Standard C Primitive Types (available in Objective-C):


Objective-C Specific Types:


Cocoa/Foundation Framework
Types:


Objective-C Numbers:



Cocoa Foundation Framework Types vs. Swift Equivalent Types:

Example: How to use a Objective-C Data Types:

 int id = 10;

 double percentage = 18.55;

 char gender = 'M';

 BOOL isVerified = YES;

 NSString *name = @"Luis A. Sierra";


 printf("Id: %d\n", id);

 printf("Name: %s\n", [name UTF8String]);

 printf("Percentage: %.2f\n", percentage);

 printf("Gender: %c\n", gender);

 printf("Verified: %s\n", isVerified ? "true" : "false");




Type Conversions

Is the process of converting one data type to another. The type conversion is only performed to those data types where conversion is possible.


Example:

int num = 10;

double dec = 5.25;

BOOL boolean = YES;


// Convert to String

printf("%s\n", [[NSString stringWithFormat:@"%d", num] UTF8String]);


// Convert to  Double

double convertedToDouble = (double)num;

printf("%f\n", convertedToDouble);


// Convert to Int

int convertedToInt = (int)dec;

printf("%d\n", convertedToInt);


// Convert to String

const char *strBool = boolean ? "true" : "false";

printf("%s\n", strBool);



MORE EXAMPLES:

* Convert to String


* Convert to Integer


* Convert to Double



* Convert to Boolean



* Convert to Date


* Convert to Time


* Convert to DateTime


* Format DateTime


* DayName of DateTime


* Convert to ASCII


* String Replace


* String Length


Arrays

An array is a data structure consisting of a collection of elements, of same memory size, each identified by at least one array index or key. An array is stored such that the position of each element can be computed from its index.


Array Length / Size


Operators

Is a character that represents a specific mathematical or logical action or process.

In Objective-C different types of operators are available; those are:

  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Misc Operators

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.


Relational Operators

Relational operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions


Logical Operators

Logical operators are used to determine the logic between variables or values:


Bitwise Operators

bitwise operators are used to perform operations directly on the binary representations of numbers.


Assignment Operators

Assignment operators are used to assign values to variables.


Misc Operators

misc operator is miscellaneous operator, are few other important operators including sizeof and ? : supported by Objective-C Language.


if/else Statement

The if-else statement is used to execute both the true part and the false part of a given condition. If the condition is true, the if block code is executed and if the condition is false, the else block code is executed


CASE Statement

The CASE expression goes through conditions and returns a value when the first condition is met (like an if-then-else statement)


For Statement

The for statement, also called the for loop, lets you repeat a statement or compound statement a specified number of times.

Example - Up:


Example - Down:


While Statement

A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.


Do While Statement

A do while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.


Method

A method in object-oriented programming (OOP) is a procedure associated with an object, and generally also a message. An object consists of state data and behavior; these compose an interface, which specifies how the object may be used. A method is a behavior of an object parametrized by a user.

Note: Methods do not return value.


Function

A function, subprogram, procedure, method, routine or subroutine is a callable unit that has a well-defined behavior and can be invoked by other software units to exhibit that behavior.

Note: functions return a value.


Class

A class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods).


Note:

Methods and functions are declared differently within a class, this is due to the design of the Objective C language.


Objects

Objects are a programming paradigm based on the concept of objects, which can contain data and code: data in the form of fields (often known as attributes or properties), and code in the form of procedures (often known as methods). In OOP, computer programs are designed by making them out of objects that interact with one another.


Constructor

In class-based, object-oriented programming, a constructor (abbreviation: ctor) is a special type of function called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required member variables.


Encapsulation

The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must declare class variables/attributes as private (cannot be accessed from outside the class). If you want others to read or modify the value of a private member, you can provide public get and set methods.


Inheritance

Inheritance is one of the core features of object-oriented programming. It's a programming procedure that allows you to reuse code by referencing the behaviors and data of an object. In other words, a class that inherits from another class shares all the attributes and methods of the referenced class.


Polymorphism

Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance.


Exception handling

Exception is typically used to denote a data structure storing information about an exceptional condition. One mechanism to transfer control, or raise an exception, is known as a throw; the exception is said to be thrown. Execution is transferred to a catch.




Post a Comment

Previous Post Next Post