Home > 2011 Fall DPS913, iOS, iOS Cocoa Touch, Mac OS X > Learning Objective-C – the top ten list

Learning Objective-C – the top ten list

December 21, 2011 Leave a comment Go to comments

When we begin to learn a new computer programming language, we often try to get acquainted with the language by applying our current knowledge to its characteristics. This “top ten” list captures this process.

.

As a third- or fourth-year student, you have some experience with a number of programming languages. Let’s begin to learn about Objective-C by asking questions in the form of a “top ten” list. (Note that you can ask these questions about ANY language.)

Note: Objective-C is the name of the programming language. It adds a small number of object-oriented extensions to the standard C language.

Cocoa is the name of the the class library and runtime. The classes are organized into “frameworks”. Your app will link to one or more frameworks.

So, in summary, to create apps for iOS and Mac OS X, you write code using the Objective-C language, and use Cocoa classes.

.

The “top ten” list of questions

Here is the “top ten” list of questions to ask when learning Objective-C:

1. How do I create/edit/save the source code? What editor do I use? Where do I store the source code? What is the source code file naming convention?

2. How do I build/compile and then execute/run my program? Is there a compiler? Is there a host execution (aka “runtime”) environment?

3. What is the program’s entry point? Syntactically, what coding convention must I follow?

4. What data types can I use? Are they categorized (e.g. value/stack, reference/heap), and if so, what do I need to know about their characteristics (e.g. size, initial value, precision, convertibility, etc.)?

5. How do I declare new variables/fields of a data type? How do I instantiate them? How do I refer to and use these variables/fields? (Note that a type could be a class declaration for an object-oriented language and platform.)

6. What operators are available to me in this language? (How do they compare to other languages that I’m familiar with?)

7. What is the syntax of a statement, and of an expression? What delimiters are used? How is scope and hierarchy expressed?

8. What syntax enables me to process a decision (e.g. if-else, or switch-case)?

9. What syntax enables me to process repeatedly (e.g. for, while)?

10. How are functions (methods) declared? What rules are there for argument/parameter declaration? How are functions used/called? Are the arguments passed by value, or by reference?

Bonus:

11. Where do I get learning/tutorial information? Where do I get reference information? Where do I look for good-quality online information?

.

The answers

Here are the answers. We cover them in class, and we go through some examples.

1. How do I create/edit/save the source code? What editor do I use? Where do I store the source code? What is the source code file naming convention?

You write source code with Xcode, Apple’s integrated development environment (IDE).

An app is typically organized as a “project”, which appears as a folder in the file system. In that folder, your source code is stored in text files, and you will also find “resources” for your app, such as images, configuration settings, and so on.

Objective-C is a header-based language. You define a class’s interface in a text file that has a .h extension (e.g. Person.h). The class’s implementation code is located in a text file that has a .m extension (e.g. Person.m).

Most often, you create classes for your app. A class can be used to perform tasks (e.g. a “controller”), or it can be used to represent real-world objects (e.g. a “model”).

.

2. How do I build/compile and then execute/run my program? Is there a compiler? Is there a host execution (aka “runtime”) environment? Does it control the application lifecycle?

In Xcode, you can use a “build” command (or one of its variants) to build/compile your program. Its command key shortcut is Command+B.

To run your program, you first select an execution target (e.g. a simulator, or a device), and then you use a “run” command. Its shortcut is Command+R.

Cocoa is the execution runtime environment. Your app runs under the control of Cocoa. Cocoa sends your app messages when something happens in the environment (e.g. a user touches/taps the screen, or data arrives from the network.

In summary, Cocoa is in control.

.

3. What is the program’s entry point? Syntactically, what coding convention must I follow?

As a C-based language, the main() function is your app’s entry point. When a user starts/launches your app, the main() function runs.

For a typical iOS or Mac OS X app, main() calls a function that loads the app into the Cocoa runtime environment. At that point in time, as noted above, the Cocoa runtime is in control.

The Xcode project templates all include the main.m source code module, which has the main() function. Typically, you do not ever have to edit main.m.

.

4. What data types can I use? Are they categorized (e.g. value/stack, reference/heap), and if so, what do I need to know about their characteristics (e.g. size, initial value, precision, convertibility, etc.)?

Your apps can use C language types, and Cocoa types, in any combination.

Most of the time, you will prefer to use Cocoa types. For example, NSString offers rich functionality for strings. NSArray is a collection class, for elements/members of any Cocoa type.

C language types, including structs, are value (scalar) types.

Cocoa type instances are reference types. The instance name is a pointer to the memory that holds the instance’s data.

The initial value of a type instance varies by type. Sometimes, you get “nil”, or nothing. Other times, you get a working object, with empty or nil fields (properties).

As you would expect, most convertible types have methods which enable type conversion. For example, NSString has an intValue method, which attempts to return an integer of the string instance.

You can create your own types. Objective-C is a header-based language:

  • The public interface (methods and properties) is defined in a source code file which has a .h extension. The definitions are placed between an @interface statement and an @end statement.
  • The implementation code is located in a source code file which has a .m extension. The code is placed between an @implementation statement and an @end statement.

.

5. How do I declare new variables/fields of a data type? How do I instantiate them? How do I refer to and use these variables/fields? (Note that a type could be a class declaration for an object-oriented language and platform.)

For C language types, simply use the C language semantics. For example:

int i = 5;

For Objective-C (Cocoa) types, you must create an instance of the desired type. There are two ways to initialize a new object:

  1. Use the type’s designated initializer
  2. Use a “class method”

.

Using an initializer:

Most Objective-C types include one or more initializer methods. (In C# and Java, you know these methods as “constructors”.)

Almost every type supports the base initializer, called “init”.

A type designer can create more initializers, which can accept arguments. If there’s more than one initializer, the type designer will make one of them the “designated initializer”, which is the one that performs the initialization. (If the developer uses another initializer, that initializer will ultimately call the designated initializer.) Initializers should always begin with “init”.

The following shows two examples that use an initializer:

NSMutableString *s = [[NSMutableString alloc] init];

Person *p = [[Person alloc] initWithLastname:@”McIntyre” andFirstName:@”Peter”];

.

Using a class method:

Many Objective-C types offer one or more class methods that initialize a new object. (In C# and Java, these are known as “static methods”.)

They are also known as “convenience” (or “factory”) methods. They make it really easy to create an object. Initializer class methods may or may not accept arguments, it depends upon their design.

The following shows two examples that use class methods. Assume that “lname” and “fname” are existing NSString objects:

NSString *s = [NSString stringWithFormat:@”My name is %@ %@”, fname, lname];

Person *p = [Person personWithFirstName:fname andLastName:lname];

.

As you would expect (in other languages), you refer to the new objects by using their instance name. You would simply use “s” to refer to the NSString object above. Or, “p” to refer to the Person object above.

As you would do in C, if you wanted the memory address of “s” or “p”, use the “&” symbol. So, the address of s would be “&s”.

As you would do in C, if you wanted the pointer to “s”, use the “*” symbol. However, as it turns out, this is infrequently used.

.

6. What operators are available to me in this language? (How do they compare to other languages that I’m familiar with?)

The standard C operators are available.

When working with objects, you will typically call an object’s methods, to perform operations, or access state through getters and setters. Some objects have properties, which you can access using a dot operator.

.

7. What is the syntax of a statement, and of an expression? What delimiters are used? How is scope and hierarchy expressed?

Standard C language rules apply for statements, expression, delimiters, scope, and hierarchy.

However, when calling a method on an Objective-C object, a square-bracket syntax is used. The syntax is obviously quite different from C and other C-family object-oriented languages.

In the example that follows, we “convert” a string, which is holding an integer, into a C scalar, by calling the string’s “intValue” method. (The string comes from a “Label” control – which is an object – in the user interface).

int n = [lblAge.Text intValue];

.

8. What syntax enables me to process a decision (e.g. if-else, or switch-case)?

Objective-C is a C-family language, so its statement syntax is similar. if-else (including the ? : syntax) and switch-case are available.

.

9. What syntax enables me to process repeatedly (e.g. for, while)?

Objective-C is a C-family language, so its statement syntax is similar. for and while are available. There is also a foreach enumerator form of the for statement.

.

10. How are functions (methods) declared? What rules are there for argument/parameter declaration? How are functions used/called? Are the arguments passed by value, or by reference?

Objective-C is a C-family language, so you declare and call functions in a similar way.

In an Objective-C class, you define (then implement) its public interface with methods and properties. There are two kinds of methods: 1) Class methods, and 2) Instance methods:

  1. A class method can be called directly, without creating an instance of the class.
  2. An instance method can be called on an instance of the class.

.

The definition of a method is similar to C, but there are two important differences:

  1. The method definition (and implementation) is preceded by a + (plus sign) for a class method, and by a – (minus sign) for an instance method.
  2. The method parameters (arguments) are named.

.

Here are a few examples, using the “Person” examples from above (in question 5).

// Instance method definition/declaration
– (NSString *)newPhoneNumber:(NSString *)phoneNumber forPhoneNumberType:(NSString *)phoneNumberType;

// Class method definition/declaration
+ (Person *)personWithFirstName:(NSString *)firstName andLastName:(NSString *)lastName;

.

The name of the instance method (above) is:

newPhoneNumber:forPhoneNumberType:

Notice that the name includes each argument, and the colons.

.

To call a method, use the syntax that you saw in question 5 above:

// Calling an instance method
Person *p = [[Person alloc] initWithLastname:@”McIntyre” andFirstName:@”Peter”];

// Calling a class method
Person *p = [Person personWithFirstName:fname andLastName:lname];

.

In Objective-C, the phrase “calling a method” is not used as a first choice. Instead, we use the phrase “sending a message (to an object)”, or more simply, “messaging”.

.

Parameters (arguments) are passed by value (like in C). However, please note that you often pass a pointer, so you are effectively passing a reference.

.

11. Where do I get learning/tutorial information? Where do I get reference information? Where do I look for good-quality online information? 

Your professor recommends the Apple developer documentation.

To get started, and learn effectively through discussion and demonstration, you must attend all lectures. Then, you can augment your learning with three kinds of Apple documentation:

1) Competencies Documents

Apple publishes two sets of well-written technology introductions. One set covers both iOS and Mac OS X, and is available here:

Cocoa Core Competencies

The other set covers topics that are specific to iOS:

Cocoa Application Competencies for iOS

Each document is a brief introduction to a topic, and includes links to a “definitive discussion” document, which is usually a developer guide.

.

2) Developer Guides 

Apple publishes a large number of developer guides. These documents range in size from tens of pages, to hundreds of pages. They include discussion, best-practice advice, code samples, and other information that’s valuable to the developer.

Developer guides are organized on a per-topic basis. You can see the complete list of guides by viewing the iOS Developer Library (after you login to the iOS Dev Center). On the left side, under “Resource Types”, click “Guides”.

A student should look for a developer guide after looking for and viewing a “competencies” document.

.

3) Reference Documents

Objective-C and Cocoa classes are well-documented in “reference” documentation. For a class reference (e.g. UITextField Class Reference), you will get overview information, as well as detailed syntax and usage for methods and properties.

.

The online iOS Dev Center is also your source for videos, code samples, Xcode information, and so on.

.

For non-Apple resources, the StackOverflow web site is acceptable. In addition, a few other web properties are useful from time to time, and they will be referenced in the notes during the semester.

Note: Your professor’s opinion is that you should avoid getting answers and code samples from search engine results. Typically, the information and code is low quality, and will distract you from learning the material. (Your professor is trying to be as kind as he can be with his phrasing here.)

.


.

.

.

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: