Extension: Cocoa Naming Conventions


The Cocoa framework and applications that use Cocoa (Touch) follow a fixed set of naming conventions that make the programs easier to read, use, and understand.

General Principles

  • Keep your code brief, but never at the expense of clarity. You’ll often see long method names in Cocoa—some programmers will complain about them, but the truth is that they make the code that much more understandable. And with Xcode’s code completion, you really don’t have to worry about all that extra typing. As an example, consider the method name removeObjectAtIndex:. That’s a very clear method name—you’re removing an object, and the argument takes an index. However, the method remove: is significantly less clear. Are you passing in an object to be removed, or an index to be removed? Or something else? The method never specifies.
  • Don’t add redundancy to names. Prefixes such as “my” or suffixes such as “object” are (almost, in the case of the latter) always unnecessary—it is obvious that it’s your variable, or that (in many cases) it’s an object.
  • 95% of the time, don’t abbreviate unless it is a well-known technical term, such as PDF or URL. Abbreviations are often not as obvious as you think they are, especially for developers from other lingual backgrounds.
  • Avoid noun/adjective-verb dualities. For instance, you may encounter a method called displayText. Does that method perform the action of displaying the text, or does it signify the text that is displayed (versus some private identifier text)? The developer has no way of knowing.
  • Consistency is important. Don’t have a count method in one class and a size method in another. Classes which have methods of the same name should do the same thing with those methods.
  • Prefixes are encouraged in Cocoa, and are used throughout Cocoa itself. Foundation and many desktop Cocoa classes begin with NS; UIKit classes begin with UI. Many developers who publish source code will prefix things with their initials, or some initialism of their company. Prefixes are especially important in determining who wrote the code, especially with generic names, such as the String class (which exists in languages such as Java).
  • Class names should have a noun involved. Other names, especially enumerated types/state representations, should have some resemblance to the class name. For example, UITableViewCell is a class, and you can specify a style using constants such as UITableViewCellStyleDefault or UITableViewCellStyleSubtitle. These constants are long, but make it clear that they work with UITableViewCell and involve its style. If you just had Default and Subtitle, they’re very ambiguous, could be used by other classes (which could lead to interesting mix-ups and collisions), and are not at all clear about what they’re referring to.
  • Categories are usually expressed as className+categoryName, such as the fictitious NSString+HTMLFormatting. Note there the “HTML” abbreviation, which is completely acceptable because HTML is widely understood.
  • Delegate and Data Source protocols will have the descriptor in the name—note UITableViewDelegate and UITableViewDataSource.
  • Other protocol names usually take a verb form of the noun they modify. For example, the NSCoding protocol works with NSCoder and NSDecoder classes.
  • Method Names

  • Method names usually begin with a lowercase letter, and each subsequent “word” in the name has its initial letter capitalized. Avoid abbreviations that are not clear. Most methods should not begin with a prefix, but you may use a prefix to denote a private method. You may also use a leading underscore (no, Apple does not reserve this method, although any Apple method with a leading underscore is supposed to be private).
  • Methods that perform an action should start with a verb. Auxiliary verbs such as “do” are not necessary and add nothing to the method except extra typing. According to the documentation, “never use adverbs or adjectives before the verb.”
  • If the method returns an attribute, the method should have the same name as the attribute, without any other modifiers, such as “calculate” or “get”. This is the naming convention that getters for properties follow.
  • Name all arguments, and make the name describe the argument. See the remove: example above.
  • Only use “and” to link two parts of a method that do different thing. For example, do not write getValue:andData:, but a method name like getValue:andDelete: is correct because it is doing two things—reading in a value and deleting (potentially) something else.
  • Verbs should not be made into adjectives. performsCalculation is preferred to calculationPerformed
  • Delegate & Data Source Methods

  • The first argument should be the object that is making the delegate or data source call. In certain cases, a class such as a view controller may be managing more than one object, such as a table view. In that case, the view controller can check to see which table view is calling the method.
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        if (tableView == tableView1)
            // return 1;
        else if (tableView == tableView2)
            // return 2;
        else
            // return something else
    }

    You’re comparing instances here, so you can use the == operator. They’ll both point to the same thing, because you’re just passing pointers around—in memory, there is only one instance of tableView1 and tableView2.

  • Delegate methods often use “did” and “will” to notify the delegate that something is about to happen, or has happened. This allows the delegate to prepare or setup some data, or to clean up after an operation. The terms provide a sense of time.
  • Methods that ask a delegate for permission, such as shouldDeleteObjectAtIndex:, should use the term “should”.
  • Miscellaneous

  • Use enumerated types, often with a typedef, to declare constants, rather than plain integers. This gives a name to the numbers, and makes it much more meaningful later. UITableViewCellStyleDefault is a lot more meaningful than simply 0.
  • Preprocessor constants are usually in all-caps, with an underscore separating the words, LIKE_THIS. Preprocessor macros maybe be named either like this, or as a standard method name; the former is preferred. Preprocessor macros defined by the compiler have leading and trailing double underscores, such as __LINE__.
  • Exceptions are named as Prefix+UniqueName+Exception, such as NSIllegalSelectorException or NSRangeException.
  • A much more in-depth look at naming conventions, along with more examples and more rules is available from Apple’s developer documentation:

    Coding Guidelines for Cocoa.

Mutable vs. Immutable Strings


As promised, some more interesting topics are on the way. Today, I stumbled across an interesting question over at StackOverflow:

Usage of NSString and NSMutableString objects in Objective C

The primary point of confusion is the exact role of NSMutableString, and how it differs from NSString. It’s a topic well worth looking into, so let’s dive right in.

Inheritance

Conveniently, NSMutableString is a subclass of NSString, which makes things a lot easier. In Java for example, the String class is barely related to the StringBuilder class (functionally similar to NSMutableString), which means that there could be constant conversions between the two classes, which is neither efficient nor convenient to code. Inheritance negates this issue.

Many methods in the Foundation and UIKit frameworks take or return NSStrings. If you had a mutable string that you meticulously constructed, you would not have to convert it to an NSString—you could just pass it right in, and reuse it as necessary. You don’t even have to cast it to an NSString. Not only is this convenient to code, it’s also more efficient. You don’t have to copy the mutable string and turn it into a regular string, which is certainly not all the efficient (relatively speaking, it could take thousands of nanoseconds, rather than the tens of nanoseconds it would take to pass a pointer). Speaking of memory, why are two separate classes needed anyway?

In-Memory

Okay, so that segue might not have made much sense. But it actually all has to do with how the strings are represented in memory. An NSString is a static block of memory that has been allocated wherever there was free space at the time. As such, you can’t shrink it, and definitely can’t add to it—shrinking it would just leave a block of garbage memory that would probably be too small to be used, and adding to it would mean taking up more memory—it could very well encroach into a block of memory that was being used elsewhere, and that would lead to very weird results. This inflexibility has an advantage though—there is only one static block of memory, and so it is very efficient. NSMutableString has a different implementation—the details of which are not public—which most likely involves multiple linked “blocks” of RAM. This linkage allows flexibility, but comes at a price of efficiency. It takes time to look up the next block and go to it (again, it’s all relatively speaking, but in the time that it take to look up the next block of memory, the system could conceptually have loaded two or even four characters, depending on if memory addresses were 32-bit or 64-bit. Each character is 16-bit). As a comparison, Java allows you to concatenate strings by using the + operator. How does it do this? By copying the old string into a new block of memory, then putting the new bit to the end of the new, bigger block. Not very efficient.

So,

When Should You Use Mutable?

A mutable string should be used when you are physically changing the value of the existing string, without completely discarding the old value. Examples might include adding a character to the beginning or the end, or changing a character in the middle. With a mutable string, you can do this “in place”—you’ll just modify the existing string. By contrast, an immutable string, once its value is set, cannot change that value. NSString has methods such as stringByAppendingString:, which does add a string to an existing one—but it returns a new string. Behind the scenes, NSString has copied your old string to a new (larger) memory location, added the argument, and returned the new string. That copying is a lot less efficient (relatively speaking, or if you have to do it a lot).

Of course, there’s nothing stopping you from physically assigning one string to another. Old values will be overwritten. Most NSStrings, including the @”String Constants”, are autoreleased. If you are creating a new string and you decide to alloc/init, you can then assign it to another value without consequence:

myString = anotherString;
myString = myTextField.text;

You can do this with both mutable and immutable strings. The main takeaway is that you should only use mutable when your changing the string itself. But you can change the variable with both mutable and immutable strings without compiler or runtime issues (short of memory management, but most of it is autoreleased anyway).

Objective-C Lesson 14: Structs and Unions


Structs

Structs are a C construct that allows for grouping of items into one variable. For example, if you wanted to store a date, you could use three separate variables for the day, month, and year. This approach would work if you had to store one or two dates. But if you’re writing a calendar application, for example, having to keep track of which month belonged with which year would be a nightmare. Fortunately, C structs allow you to group these values into one type. The syntax for a date struct might look like this:

struct date {int month; int day; int year;};

You can then define a variable of this type as struct date today, yesterday;. However, we can use our friend the typedef statement to make this code a bit neater:

typedef struct {int month; int day; int year;} Date;
Date today, yesterday;

To access values within a struct, you use the dot operator. To set the month, you might write today.month = 5;. To get a value, the same procedure applies: int year = today.year;.

In action, it might look like this:

#import 

int main (int argc, char *argv[]) {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	typedef struct {int month; int day; int year;} Date;
	Date today;
	today.month = 5;
	today.day = 22;
	today.year = 2011;
	
	NSLog(@"Today's date is %i/%i/%i", today.month, today.day, today.year);
	[pool drain];
	return 0;
}

Initializing Structures

The fastest way to initialize a structure is to enclose the values in a pair of braces:

Date today = {5, 22, 2011};

You can list fewer values, and they will be filled in until the end of the values you list. The remaining values will be undefined.

Date today = {5};

This sets the month to 5, but leaves the remaining fields with garbage values from RAM.

You can also initialize the values out of order:

Date today = {.day = 22, .month = 5; .year = 2011};

Structs Within Structs

C allows you to put structs with structs. For example, Apple provides the CGRect data type, which defines a data type by being a struct containing a CGPoint and CGSize:

struct CGRect {
   CGPoint origin;
   CGSize size;
};
typedef struct CGRect CGRect;

You can then access the values by chaining the dot operator. To get the width, you would write

float width = rect.size.width;

Unions

Unions are a data construct that allow you to store more than one type of data in the same storage area. They are typically used in more advanced constructs. If you needed a variable, x, that could hold either an int, float, or char type, you could define a union as such:

union mixed {int i; float f; char c;};

Unions are syntactically similar to structs, but inside there are not three pieces of memory, only one. You can used the mixed type to hold either an int, or float, or char, but not two at the same time. Setting a new value overrides the previous, and you must ensure that you pull out the same type as you put in; otherwise you’ll get strange results. Accessing the field is the same as with a struct:

// x is such a union type
x.c = 'E';
x.f = 39.28;
x.i = 7/2;

You can initialize the union with a single value in braces, and it will be assigned to the first field:

union mixed x = {'$'};
// You can also specify a field
union mixed x = {.f = 3.14};

Structs and unions are more advanced C data types that are nonetheless used in lower-level frameworks, such as Apple’s Quartz framework for drawing stuff to the screen. It is important to realize that they are not objects, though. They are merely data types, with no methods to access.

Shameless Self-Promotion


To get the word out, I’d generally rely on search engines. And I can’t afford to pay Google to get listed (and most of those ads aren’t exactly reputable anyway). So, here’s some shameless self promotion. I promise I won’t really do this much more. Feel free to not read this. You may want to entertain yourself elsewhere (I’d recommend Uncyclopedia).


Cups of Cocoa Cups of Cocoa Cups of Cocoa Cups of Cocoa Cups of Cocoa Cups of Cocoa Cups of Cocoa Cups of Cocoa

iPhone App Development iPhone App Development iPhone App Development iPhone App Development

iPhone Application Development iPhone Application Development iPhone Application Development

Programming for iOS Programming for iOS Programming for iOS Programming for iOS Programming for iOS

iPhone App iPhone App iPhone App iPhone App iPhone App iPhone App iPhone App iPhone App iPhone App

iPhone Apps iPhone Apps iPhone Apps iPhone Apps iPhone Apps iPhone Apps iPhone Apps iPhone Apps

Creating iPhone Apps Creating iPhone Apps Creating iPhone Apps Creating iPhone Apps Creating iPhone Apps

iPhone Programming iPhone Programming iPhone Programming iPhone Programming iPhone Programming iPhone Programming

Developer Developer Developer Developer Developer Developer Developer Developer Developer Developer Developer

iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS iOS

App Store App Store App Store App Store App Store App Store App Store App Store App Store App Store App Store

Programming Programming Programming Programming Programming Programming Programming

iPhone iPhone iPhone iPhone iPhone iPhone iPhone iPhone iPhone iPhone iPhone iPhone iPhone

iPod Touch iPod Touch iPod Touch iPod Touch iPod Touch iPod Touch iPod Touch iPod Touch

iPad iPad iPad iPad iPad iPad iPad iPad iPad iPad iPad iPad iPad iPad iPad iPad iPad iPad iPad iPad

Xcode Xcode Xcode Xcode Xcode Xcode Xcode Xcode Xcode Xcode Xcode Xcode Xcode Xcode Xcode

Objective-C Objective-C Objective-C Objective-C Objective-C Objective-C Objective-C Objective-C

Apple Apple Apple Apple Apple Apple Apple Apple Apple Apple Apple Apple Apple Apple Apple Apple

Cocoa Cocoa Cocoa Cocoa Cocoa Cocoa Cocoa Cocoa Cocoa Cocoa Cocoa Cocoa Cocoa Cocoa Cocoa

iPhone SDK iPhone SDK iPhone SDK iPhone SDK iPhone SDK iPhone SDK iPhone SDK iPhone SDK

Software Software Software Software Software Software Software Software Software Software Software

Object-Oriented Programming Object-Oriented Programming Object-Oriented Programming Object-Oriented Programming


😀

Extending “Hello, World!”


Now that you understand how the “Hello World” program works, let’s add the phrase “I’m ready to program in Objective-C!” to the output. Simply add another NSLog statement to the program. The solution is below, but try to figure out the problem for yourself.


/* Add the phrase
"I'm ready to program in Objective-C!"
to the output */

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        NSLog (@"Hello, World!");
        NSLog (@"I'm ready to program in Objective-C!");

        [pool drain];
        return 0;
}

Build and Run the program. The output should be the same as below:

Hello, World!
I'm ready to program in Objective-C!

The NSLog calls automatically create a paragraph break, or a new line, between subsequent calls. It does this automatically, but you can also force a new line in the middle of an NSLog call by using \n anywhere in the line of output. Therefore,

NSLog (@"Hello, World! \nI'm ready to program in Objective-C!");

Produces the same output as above.

Objective-C Lesson 1: Hello World!


Note: Click on any image to see a larger version.

Since Dennis Ritchie demoed the C programming language, it has been conventional to begin a programming course with a program that writes the words “Hello world!” to the computer screen. Diving right in, the code is shown below.

Program 1.1

// First program example

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        NSLog (@"Hello, World!");
        [pool drain];
        return 0;
}

Using Xcode

So what does all this gibberish mean? Before we can get to that, we’ll run the program first.

Download a copy of Xcode, if you don’t have it already, and install it. Navigation to your boot drive (usually Macintosh HD), and the folder called Developer. Inside, there will be a folder called Applications. Xcode, and some other programs you will be using, is in there.

Xcode is located at /Developer/Applications

Location of Xcode.app

Drag it to your dock, or create an alias for it in your Applications folder. Launch Xcode. The first thing you’ll see is the launch window:

Xcode Launch Window (With Highlighting)

Xcode Launch Window (New Project Highligted)

Click on “Create a new Xcode project,” or select File > New Project (⇧⌘N). The button is highlighted in the image above. You will be greeted by the following window:

Xcode's New Image Window

Xcode's New Image Window

Select Application under Mac OS X on the left, and choose Command Line Tool on the right. Make sure the Type drop-down menu in the middle is set to Foundation. Click Choose…

Name your project, and save it somewhere on your hard drive. In a few moments, you’ll see Xcode’s main interface:

Xcode

Xcode's Main Window

We’ll take more about the parts of the window in later sections. Click on the file called Hello World.m, or something similar. This should bring up the editor window. Replace the code in the editor view with the code above, so that it looks like this:

Hello, World entered in Xcode

The Code in Xcode's Editor

Don’t worry about all the colors—we’ll discuss that later. When you have entered the code, save the file, and click the “Build and Run” or “Build and Go” button in the toolbar.

If you’ve made a mistake when typing it in, the toolbar at the bottom of Xcode’s window will change, and a message bubble will appear:

Xcode tells you when you've made a mistake

Xcode Tells You About Errors

Go back, and check the code.

When everything is working, you’ll see yet another window:

Xcode Displays the Result of the Code in the Console

Xcode Displays the Result of the Program

The output is as follows:

2010-09-03 10:47:32.414 Hello World[25379:a0f] Hello, World!

The beginning of the line shows the date and time, followed by the name of the program, and bunch of gibberish. But at the end of the line is the text that you expected to see: The program has written the words “Hello, World!” onto the screen.

Throughout the rest of these tutorials, the text that appears before that actual text that is outputted will be omitted for brevity.

Code, Demystified

Now that you’ve created a working program, let’s talk about how it works.

In Objective-C, a capital and lowercase letter mean different things. So, main, Main, and mAin are three completely different things, and cannot be used interchangeably. Also note that white space—spaces, tabs, and blank lines are ignored. You can use this to format your code properly. Take advantage of this freedom to properly format your code.

The first line of the program is a comment:

// First program example

Comments exist solely for the benefit of the programmer. Comments are important, because they allow the developer to explain a thought process. They help demystify the code, and make documenting the code sometime down the road easier. Comments help during the debugging process, or when you revisit your code some time later. It also helps other people who may use your code understand why things are the way the are. The compiler ignores comments, so you can type anything into a comment.

There are two types of comments in Objective-C. One is shown above, in which every line of the comment is preceded by two slashes. This type of comment ends at the end of the line.

A comment can also be written across multiple lines, with the following syntax:

/*
A multi-line comment can be inserted
by using a slash
and then an asterisk.
The comment can be as long as you want,
but make sure you close it
with an asterisk, then a slash. */

Which style you choose is a matter of preference, or as the situation dictates.

The next line of the program imports, or brings into your project, a file called Foundation.h:

#import <Foundation/Foundation.h>

The file in question is a system file, and that is why the name is enclosed in the brackets < and >. If you were importing a local file , you would enclose the file name in double quotes “ and ”.  This file is imported because code later in the file requires information that is contained in this file;  you are telling the compiler to look up the information in that file as necessary.

The following line declares a function called main:

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

main is a function that is where every C or C-based program begins. It is a reserved name, which means that you can’t have a function named main. The word int that precedes main is a declaration of the return type of the function. These topics will be discussed in further chapters.

After identifying main to the compiler, you tell the system what to do when it is called. These statements are enclosed in the braces { and } that surround the next few lines. Every opening brace has to be matched with a closing brace.

The first statement in main is as follows:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

This involves memory management, which is a topic thoroughly discussed in upcoming chapters.

The next line calls NSLog, which, along with the NSAutoreleasePool from above, is a function brought in by Foundation.h, which you imported.

NSLog (@"Hello, World!");

This line tells the function NSLog, which is designed to output text, to print the characters Hello, World! on the screen.

The leading @ in front of the string signifies to the compiler that this is an NSString (another object brought in from the Foundation.h file), not a C-style string. For the most part, you will be using NSStrings, rather than C-style strings.

All statements, or lines that indicate some action, must be terminated with a semicolon ; just like regular sentences are terminated with a period.

The next line is part of the NSAutoreleasePool, and its purpose and meaning will be discussed in a later chapter.
The final line tells the main method to return the value 0. Remember that the int the preceded main tells the system that this function will return a value. This value is 0. By convention, a return value of zero indicates that the function was successful.

return 0;

This line is followed by a closing brace, signifying the end of the main function.

If you look back at the window that displays the output of your program, you should see the line

Program exited with status value:0.

This is an indication of the return value of main.

Congratulations, you have created your first program in Objective-C!

  • Welcome

    My goal is to make CupsOfCocoa into a beautiful source for beginners to the iPhone platform to get started. Subscribe below for more, and stay tuned!

  • Contact Me

    If you need to contact me for any reason, feel free to send me an email.
  • The Giving Spirit

    If you've found this site helpful, would you consider donating a little sum? Any amount is appreciated...Thanks so much!

  • Roadmap

  • Enter your email address to follow this blog and receive notifications of new posts by email.

    Join 220 other followers

  • Back to the Past

    May 2020
    S M T W T F S
     12
    3456789
    10111213141516
    17181920212223
    24252627282930
    31  
  • Time Machine

  • You count!

    • 622,650 views
  • Worldwide Stats

    free counters
%d bloggers like this: