DPS923 notes – Tue Apr 14

Objective-C language introduction, and using Objective-C in a Swift app.

.

Objective-C language introduction

Until the release of Swift in 2014, the Objective-C language was used exclusively to create applications for iOS and Mac OS X.

Objective-C is a strict superset of C. It adds a small number of features to C, enabling object-oriented capabilities.

Notably, it also provides dynamic typing and binding, deferring many operations until runtime, in contrast to many other statically-typed languages you use, including Swift and C++.

.

Brief history

Objective-C was created in the early 1980s by Brad Cox and Tom Love.

Its features were influenced by the Smalltalk language, which was the ‘next big thing’ in computer programming languages in the late 1970s and early 1980s.

NeXT – the company Steve Jobs created after leaving Apple in 1985 – selected Objective-C for its programming environment. It was combined with libraries and developer tools into the NeXTSTEP operating system for NeXT computers. Apple acquired NeXT at the end of 1996. NeXTSTEP became the base for Mac OS X (released in 2001), and iOS (released in 2007).

Tim Berners-Lee – inventor of the web – used NeXT computers to write the software for the first web server and first web browser.

.

Notably, work on the Objective-C language started in the same year as, but independently of, Bjarne Stroustrup‘s work on what became C++. His work was influenced by the Simula language.

For beginners, especially those (like you) who have been learning Simula-influenced languages (C++, Java, C#), the Smalltalk vs. Simula difference completely explains the odd-looking syntax in Objective-C.

.

Most obvious differences

For beginners, the two most obvious differences in Objective-C, when compared to Simula-influenced languages, are:

  1. New syntax
  2. Terminology

.

New syntax

There are three significant new syntax approaches that you must learn immediately:

  1. Use of the @ prefix
  2. Method declaration style
  3. Method invocation (calling) style

.

Use of the @ prefix

Compiler directives use the at sign – @ – for many tasks. The most obvious include the following examples.

Key words, identifying a C-style ‘header’ file – @interface – and its implementation – @implementation.

Class members for state persistence, known as ‘declared properties’, are identified with @property.

The Objective-C ‘string object‘ – when contrasted with a C-style string (e.g. char *) – has an at-sign prefix, e.g. @”Hello, world!”.

.

Method declaration style

Like many object-oriented environments, a class can have instance methods, and/or methods that belong to the class itself (known as class or static methods).

The code for instance methods is prefixed with a minus sign (aka dash).

The code for class methods is prefixed with a plus sign.

After the – or +, the method’s return type is declared, enclosed in C-style parentheses. For example:

– (NSString *)doSomething…

– (NSArray *)getCollection…

+ (void)somethingElse…

A method can have a parameter. It is declared with a colon, a type, and a name to be used in the method body. For example:

– (NSString *)getFirstName:(NSString *)firstName
{ … }

A method can have more than one parameter. A space (character) is used as a separator. Each parameter has an external name (used when invoking the method), and a name to be used in the method body. For example:

– (NSString *)getFirstName:(NSString *)firstName andLastName:(NSString *)lastName
{ … }

When a method has more than one parameter, its full, complete, and correct method name is a multi-part name, composed of the method name and its parameter names, using a colon separator. A method name can be used in conversational speech or in descriptive documentation. The name of the example method in the previous paragraph is:

getFirstName:andLastName:

.

Method invocation style

Method invocation – calling a method – uses square brackets to surround the expression.

Like other object-oriented programming languages, you call a method on an instance of the class, or on the class itself (for a class or static method).

Assume that you have a reference to an object named “user”, and its class has the getFirstName:andLastName: method, as in the previous section. The method is invoked as follows:

NSString *userFullName = [user getFirstName:@”Peter” andLastName:@”McIntyre”];

.

Terminology

Programmers who learned Simula-influenced languages use terms that are well-understood within those language communities.

Objective-C terminology can seem quite different. Here’s a sampling of Objective-C terms:

Send a message = invoke/call a method

Interface source code = header file

Protocol source code = abstract base class with pure virtual methods (aka an ‘interface’ in C#)

Initializer = constructor

Declared property = class member for state persistence (aka ‘property’ in C#)

Category = extension method (in Swift or C#)

self = this (in C++ or C#), which is the name of a pointer to the object instance

.

Other notable differences

Other notable differences include:

New types:

  • id – similar to void * – used to define ‘an object of any type’ (determined at runtime)
  • BOOL – a typedef signed char, 0 = NO, and 1 = YES
  • nil – a pointer, with a value of 0, used to point to a non-existent object type
  • types provided by the Foundation library (e.g. NSString, NSArray, NSDate, etc.)

In a source code file, the #import statement is used instead of include. They’re similar in purpose, but #import ensures that the named library (or header) is included only once during the compilation process, even if the statement appears in many source code files.

.

The Cocoa frameworks

Adapted from Apple’s published introduction, the Cocoa frameworks consist of libraries, APIs, and runtimes that form the development layer for apps that run on iOS and OS X.

The Cocoa frameworks are vast, providing a rich set of objects that you can use to build software. It includes common and expected types, like NSString and NSArray, as well as richly functional specialized types, like NSFetchedResultsController.

Cocoa also provides a runtime that manages the lifetime and execution environment of your app, when running on a device.

.

An iOS project in Objective-C

An iOS project that uses only the Objective-C language has a structure that’s similar to that of a Swift-language project. There are two visible differences in Objective-C projects:

  1. main.m
  2. the source code for a class is split into two files, an interface, and an implementation

.

main.m

The entry point in any C program is the main function. In an iOS project, the function is in the main.m source code file.

Its source code simply starts the Cocoa runtime environment, which then begins loading the app, beginning with the app delegate, the app’s initial scene, and the scene’s controller.

.

Class source code files

By design, the source code for a class is split into two files. The filename part of both files is, by convention, the class name.

The interface file has a ‘h’ suffix (file extension). For example, “Person.h”. The interface is publicly-visible, and like C, its purpose is to enable potential users to learn about the class members.

The implementation file has a ‘m’ suffix. For example, “Person.m”. The implementation has the program code that implements the class members and its functionality.

.

Objective-C classes

When writing an Objective-C class, you begin with the interface source code file. In Xcode, the ‘new class’ template will create both files, and the editor will open and display the interface source code file.

Classes contain all or some of these members:

  • private variables
  • private methods (i.e. ‘functions’)
  • public declared properties (state/data)
  • public methods (functionality)

.

Private variables are declared in a { } code block immediately after the @interface or @implementation key word.

Private methods are typically declared in the implementation source code file, in a code block immediately after the @implementation key word (perhaps along with private variables).

Public declared properties are declared in the interface source code file, with memory-management attributes (i.e. declarations). In the implementation, code uses the ‘self’ prefix to get a reference to the declared property (e.g. self.FirstName).

Public methods are declared in the interface source code file. Then, their method bodies are coded in the implementation source code file.

.

Declaring variables

When declaring variables that have a C type, use the familiar syntax, for example:

int age = 22;

double cost = 3.49;

When declaring variables that use an Objective-C type (including the wide range of types in the Cocoa frameworks), use the familiar syntax for pointers, for example:

NSString *firstName = @”Peter”;

The Objective-C coding style, or convention, states that you should separate the type name and the asterisk with a space. Then, at your option, you can use a space separator – or not – between the asterisk and the variable name. Your professor prefers to omit the space, as shown above.

Like C, “firstName” will point to an area of memory that holds its data. In statements, we simply use the “firstName” variable name to refer to the object.

.

Getting help

Apple has published a guide to help you work with Swift and Objective-C:

Using Swift with Cocoa and Objective-C

.

Example coding scenario

Today, in class, we will work through a coding scenario.

We will start with a working app, which was written in Objective-C.

Then, we will “upgrade” one of its controllers to use Swift.

.

Bridging header

In projects that mix the two languages, Xcode will offer to create a ‘bridging header’ source code file when it first detects the use of the other language:

xcode-bridging-header-create

.

The purpose of this file is to declare the Objective-C header files that Swift classes need to know about. It is an Objective-C source code file.

For example, in today’s coding scenario, the new Swift controller will need to know about the existing Model class, as well as another controller class, which declares a protocol.

The header file has this code:

#import "Model.h"
#import "SelectColour.h"

.

Another coding scenario

In last Thursday’s class, your professor was asked whether it was possible to add pinch-and-zoom, and rotation, to the ShapesV4 code example.

A quick web search revealed an article on Ray Wenderlich’s web site:

UIGuestureRecognizer Tutorial

From 2011, it covered the topic using Objective-C. Your professor ignored the link to the Swift version of the tutorial, because he felt like a challenge.

The pinch-and-zoom and rotation functionality was translated in real time to a Swift version. We’ll inspect the results today.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: