Objective-C in Action

This section touches upon the more frequently used aspects of the Objective-C language, using code snippets where appropriate to illustrate how the language constructs are actually used in the context of an application. Don’t worry if you don’t completely understand every detail in every section. Objective-C is easy to pick up by example, and you’ll have plenty of time to absorb it as you work through the tutorials in the later chapters.

Declarations

Objects can be declared statically or dynamically. Statically typed objects are declared as a pointer to a class:

NSString *mystring;

Static typing results in better compile-time type checking and makes code easier to understand. Note that in the previous example, mystring doesn’t have to be an instance of NSString; it could also be an instance of any class that inherits from NSString.

Dynamically typed objects are declared as id:

id myObject;

Since the class of dynamically typed objects is resolved at runtime, you can refer to them in your code without knowledge of their class membership. Type objects in this way if they are likely to be involved in polymorphism and dynamic binding.

Declarations of instance methods begin with a minus sign (-); a space after the minus sign is optional:

- (NSString *)countryName;

Put the type of value returned by a method in parentheses between the minus sign (or plus sign) and the beginning of the method name. Methods that return nothing should have a return type of ...

Get Learning Cocoa now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.