Home > Articles > Programming > General Programming/Other Languages

This chapter is from the book

Using Existing Classes

If it isn’t running, start Xcode. Close any projects that you were working on. Under the File menu, choose New -> New Project.... When the panel pops up, choose to create a Command Line Tool (Figure 3.1).

Figure 3.1.

Figure 3.1. Choose Project Type

A command-line tool has no graphical user interface and typically runs on the command line or in the background as a daemon. Unlike in an application project, you will always alter the main function of a command-line tool.

Name the project lottery (Figure 3.2). Unlike the names of applications, most tool names are lowercase. Set the Type to Foundation.

Figure 3.2.

Figure 3.2. Name Project

When the new project appears, select main.m in the lottery group. Edit main.m to look like this:

#import <Foundation/Foundation.h>

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

        NSMutableArray *array;
        array = [[NSMutableArray alloc] init];
        int i;
        for (i = 0; i < 10; i++) {
            NSNumber *newNumber =
                          [[NSNumber alloc] initWithInt:(i * 3)];
            [array addObject:newNumber];
        }
        for ( i = 0; i < 10; i++) {
            NSNumber *numberToPrint = [array objectAtIndex:i];
            NSLog(@"The number at index %d is %@",  i, numberToPrint);
        }

   }
    return 0;
}

Here is the play-by-play for the code:

#import <Foundation/Foundation.h>

You are including the headers for all the classes in the Foundation framework. The headers are precompiled, so this approach is not as computationally intensive as it sounds.

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

The main function is declared just as it would be in any Unix C program.

@autoreleasepool {

This code defines an autorelease pool for the code enclosed by the braces. We will discuss the importance of autorelease pools in the next chapter.

NSMutableArray *array;

One variable is declared here: array is a pointer to an instance of NSMutableArray. Note that no array exists yet. You have simply declared a pointer that will refer to the array once it is created.

array = [[NSMutableArray alloc] init];

Here, you are creating the instance of NSMutableArray and making the array variable point to it.

for (i = 0; i < 10; i++) {
    NSNumber *newNumber = [[NSNumber alloc] initWithInt:(i*3)];
    [array addObject:newNumber];
}

Inside the for loop, you have created a local variable called newNumber and set it to point to a new instance of NSNumber. Then you have added that object to the array.

The array does not make copies of the NSNumber objects. Instead, it simply keeps a list of pointers to the NSNumber objects. Objective-C programmers make very few copies of objects, because it is seldom necessary.

for ( i = 0; i < 10; i++) {
    NSNumber *numberToPrint = [array objectAtIndex:i];
    NSLog(@"The number at index %d is %@", i, numberToPrint);
}

Here, you are printing the contents of the array to the console. NSLog is a function much like the C function printf(); it takes a format string and a comma-separated list of variables to be substituted into the format string. When displaying the string, NSLog prefixes the generated string with the name of the application and a time stamp.

In printf, for example, you would use %x to display an integer in hexadecimal form. With NSLog, we have all the tokens from printf and the token %@ to display an object. The object gets sent the message description, and the string it returns replaces %@ in the string. We will discuss the description method in detail soon.

All the tokens recognized by NSLog() are listed in Table 3.1.

Table 3.1. Possible Tokens in Objective-C Format Strings

Symbol

Displays

%@

id

%d, %D, %i

long

%u, %U

unsigned long

%hi

short

%hu

unsigned short

%qi

long long

%qu

unsigned long long

%x, %X

unsigned long printed as hexadecimal

%o, %O

unsigned long printed as octal

%f, %e, %E, %g, %G

double

%c

unsigned char as ASCII character

%C

unichar as Unicode character

%s

char * (a null-terminated C string of ASCII characters)

%S

unichar * (a null-terminated C string of Unicode characters)

%p

void * (an address printed in hexadecimal with a leading 0x)

%%

a % character

Our main() function ends by returning 0, indiciating that no error occurred:

    return 0;
}

Run the completed command-line tool (Figure 3.3). (If your console doesn’t appear, use the View -> Show Debug Area menu item and ensure that the console, the right half, is enabled.)

Figure 3.3.

Figure 3.3. Completed Execution

Sending Messages to nil

In most object-oriented languages, your program will crash if you send a message to null. In applications written in those languages, you will see many checks for null before sending a message. In Java, for example, you frequently see the following:

if (foo != null) {
    foo.doThatThingYouDo();
}

In Objective-C, it is okay to send a message to nil. The message is simply discarded, which eliminates the need for these sorts of checks. For example, this code will build and run without an error:

id foo;
foo = nil;
int bar = [foo count];

This approach is different from how most languages work, but you will get used to it.

You may find yourself asking over and over, “Argg! Why isn’t this method getting called?” Chances are that the pointer you are using, convinced that it is not nil, is in fact nil.

In the preceding example, what is bar set to? Zero. If bar were a pointer, it would be set to nil (zero for pointers). For other types, the value is less predictable.

NSObject, NSArray, NSMutableArray, and NSString

You have now used these standard Cocoa objects: NSObject, NSMutableArray, and NSString. (All classes that come with Cocoa have names with the NS prefix. Classes that you will create will not start with NS.) These classes are all part of the Foundation framework. Figure 3.4 shows an inheritance diagram for these classes.

Figure 3.4.

Figure 3.4. Inheritance Diagram

Let’s go through a few of the commonly used methods on these classes. For a complete listing, you can access the online documentation in Xcode’s Help menu.

NSObject

NSObject is the root of the entire Objective-C class hierarchy. Some commonly used methods on NSObject are described next.

- (id)init

Initializes the receiver after memory for it has been allocated. An init message is generally coupled with an alloc message in the same line of code:

TheClass *newObject = [[TheClass alloc] init];
- (NSString *)description

Returns an NSString that describes the receiver. The debugger’s print object command (“po”) invokes this method. A good description method will often make debugging easier. Also, if you use %@ in a format string, the object that should be substituted in is sent the message description. The value returned by the description method is put into the log string. For example, the line in your main function

NSLog(@"The number at index %d is %@", i, numberToPrint);

is equivalent to

NSLog(@"The number at index %d is %@", i,
                            [numberToPrint description]);
- (BOOL)isEqual:(id)anObject

Returns YES if the receiver and anObject are equal and NO otherwise. You might use it like this:

if ([myObject isEqual:anotherObject]) {
    NSLog(@"They are equal.");
}

But what does equal really mean? In NSObject, this method is defined to return YES if and only if the receiver and anObject are the same object—that is, if both are pointers to the same memory location.

Clearly, this is not always the “equal” that you would hope for, so this method is overridden by many classes to implement a more appropriate idea of equality. For example, NSString overrides the method to compare the characters in the receiver and anObject. If the two strings have the same characters in the same order, they are considered equal.

Thus, if x and y are NSStrings, there is a big difference between these two expressions:

x == y

and

[x isEqual:y]

The first expression compares the two pointers. The second expression compares the characters in the strings. Note, however, that if x and y are instances of a class that has not overridden NSObject’s isEqual: method, the two expressions are equivalent.

NSArray

An NSArray is a list of pointers to other objects. It is indexed by integers. Thus, if there are n objects in the array, the objects are indexed by the integers 0 through n – 1. You cannot put a nil in an NSArray. (This means that there are no “holes” in an NSArray, which may confuse some programmers who are used to Java’s Object[].) NSArray inherits from NSObject.

An NSArray is created with all the objects that will ever be in it. You can neither add nor remove objects from an instance of NSArray. We say that NSArray is immutable. (Its mutable subclass, NSMutableArray, will be discussed next.) Immutability is nice in some cases. Because it is immutable, a horde of objects can share one NSArray without worrying that one object in the horde might change it. NSString and NSNumber are also immutable. Instead of changing a string or number, you will simply create another one with the new value. (In the case of NSString, there is also the class NSMutableString that allows its instances to be altered.)

A single array can hold objects of many different classes. Arrays cannot, however, hold C primitive types, such as int or float.

Here are some commonly used methods implemented by NSArray:

- (unsigned)count

Returns the number of objects currently in the array.

- (id)objectAtIndex:(unsigned)i

Returns the object located at index i. If i is beyond the end of the array, you will get an error at runtime.

- (id)lastObject

Returns the object in the array with the highest index value. If the array is empty, nil is returned.

- (BOOL)containsObject:(id)anObject

Returns YES if anObject is present in the array. This method determines whether an object is present in the array by sending an isEqual: message to each of the array’s objects and passing anObject as the parameter.

- (unsigned)indexOfObject:(id)anObject

Searches the receiver for anObject and returns the lowest index whose corresponding array value is equal to anObject. Objects are considered equal if isEqual: returns YES. If none of the objects in the array are equal to anObject, indexOfObject: returns NSNotFound.

NSMutableArray

NSMutableArray inherits from NSArray but extends it with the ability to add and remove objects. To create a mutable array from an immutable one, use NSArray’s mutableCopy method.

Here are some commonly used methods implemented by NSMutableArray:

- (void)addObject:(id)anObject

Inserts anObject at the end of the receiver. You are not allowed to add nil to the array.

- (void)addObjectsFromArray:(NSArray *)otherArray

Adds the objects contained in otherArray to the end of the receiver’s array of objects.

- (void)insertObject:(id)anObject atIndex:(unsigned)index

Inserts anObject into the receiver at index, which cannot be greater than the number of elements in the array. If index is already occupied, the objects at index and beyond are shifted up one slot to make room. You will get an error if anObject is nil or if index is greater than the number of elements in the array.

- (void)removeAllObjects

Empties the receiver of all its elements.

- (void)removeObject:(id)anObject

Removes all occurrences of anObject in the array. Matches are determined on the basis of anObject’s response to the isEqual: message.

- (void)removeObjectAtIndex:(unsigned)index

Removes the object at index and moves all elements beyond index down one slot to fill the gap. You will get an error if index is beyond the end of the array.

As mentioned earlier, you cannot add nil to an array. Sometimes, you will want to put an object into an array to represent nothingness. The NSNull class exists for exactly this purpose. There is exactly one instance of NSNull, so if you want to put a placeholder for nothing into an array, use NSNull like this:

[myArray addObject:[NSNull null]];

NSString

An NSString is a buffer of Unicode characters. In Cocoa, all manipulations involving character strings are done with NSString. As a convenience, the Objective-C language also supports the @"..." construct to create a string object constant from a 7-bit ASCII encoding:

NSString *temp = @"this is a constant string";

NSString inherits from NSObject. Here are some commonly used methods implemented by NSString:

- (id)initWithFormat:(NSString *)format, ...

Works like sprintf. Here, format is a string containing tokens, such as %d. The additional arguments are substituted for the tokens:

int x = 5;
char *y = "abc";
id z = @"123";
NSString *aString = [[NSString alloc] initWithFormat:
            @"The int %d, the C String %s, and the NSString %@",
            x, y, z];
- (NSUInteger)length

Returns the number of characters in the receiver.

- (NSString *)stringByAppendingString:(NSString *)aString

Returns a string object made by appending aString to the receiver. The following code snippet, for example, would produce the string “Error: unable to read file.”

NSString *errorTag = @"Error: ";
NSString *errorString = @"unable to read file.";
NSString *errorMessage;
errorMessage = [errorTag stringByAppendingString:errorString];

- (NSComparisonResult)compare:(NSString *)otherString

Compares the receiver and otherString and returns NSOrderedAscending if the receiver is alphabetically prior to otherString, NSOrderedDescending if otherString is comes before the receiver, or NSOrderedSame if the receiver and otherString are equal.

- (NSComparisonResult)caseInsensitiveCompare:(NSString *)
otherString

Like compare:, except the comparison ignores letter case.

“Inherits from” versus “Uses” or “Knows About”

Beginning Cocoa programmers are often eager to create subclasses of NSString and NSMutableArray. Don’t. Stylish Objective-C programmers almost never do. Instead, they use NSString and NSMutableArray as parts of larger objects, a technique known as composition. For example, a BankAccount class could be a subclass of NSMutableArray. After all, isn’t a bank account simply a collection of transactions? The beginner would follow this path. In contrast, the old hand would create a class BankAccount that inherited from NSObject and has an instance variable called transactions that would point to an NSMutableArray.

It is important to keep track of the difference between “uses” and “is a subclass of.” The beginner would say, “BankAccount inherits from NSMutableArray.” The old hand would say, “BankAccount uses NSMutableArray.” In the common idioms of Objective-C, “uses” is much more common than “is a subclass of.”

You will find it much easier to use a class than to subclass one. Subclassing involves more code and requires a deeper understanding of the superclass. By using composition instead of inheritance, Cocoa developers can take advantage of very powerful classes without really understanding how they work.

In a strongly typed language, such as C++, inheritance is crucial. In an untyped language, such as Objective-C, inheritance is just a hack that saves the developer some typing. There are only two inheritance diagrams in this entire book. All the other diagrams are object diagrams that indicate which objects know about which other objects. This is much more important information to a Cocoa programmer.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020