Graphics Programs Reference
In-Depth Information
Exceptions and Unrecognized Selectors
An object only responds to a message if its class implements the associated method.
Objective-C is a dynamically-typed language, so it can't always figure out at compile time
(when the application is built) whether an object will respond to a message. Xcode will
give you an error if it thinks you are sending a message to an object that won't respond, but
if it isn't sure, it will let the application build.
If, for some reason (and there are many), you end up sending a message to an object that
doesn't respond, your application will throw an exception . Exceptions are also known as
run-time errors because they occur once your application is running as opposed to compile-
time errors that show up when your application is being built, or compiled. (We'll come
back to compile-time errors in Chapter 4 .)
To practice dealing with exceptions, we're going to cause one in RandomPossessions . In
BNRItem.h , declare a new method:
@interface BNRItem : NSObject
{
NSString *itemName;
NSString *serialNumber;
int valueInDollars;
NSDate *dateCreated;
}
- (void)doSomethingWeird;
+ (id)randomItem;
You are going to send the message doSomethingWeird to an instance of BNRItem .
The problem? You didn't implement doSomethingWeird in BNRItem.m - you only
declared it in BNRItem.h . Therefore, BNRItem does not implement doSo-
methingWeird , and an exception will be thrown. In main.m , send this message to a
BNRItem .
for (int i = 0; i < 10; i++) {
BNRItem *p = [BNRItem randomItem];
[p doSomethingWeird];
[items addObject:p];
}
Build and run the application. Your application will compile, start running, and then halt.
Check your console and find the line that looks like this:
2011-11-14 12:23:47.990 RandomPossessions[10288:707] ***
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason:
Search WWH ::




Custom Search