To make it more clear what I am talking about, here's an example.
Having this class:
@interface Person : NSObject {
NSString *name;
}
@property (nonatomic, retain) NSString *name;
- (void)sayHi;
@end
with this implementation:
@implementation Person
@synthesize name;
- (void)dealloc {
[name release];
[super dealloc];
}
- (void)sayHi {
NSLog(@"Hello");
NSLog(@"My name is %@.", name);
}
@end
Somewhere in the program I do this:
Person *person = nil;
//person = [[Person alloc] init]; // let's say I comment this line
person.name = @"Mike"; // shouldn't I get an error here?
[person sayHi]; // and here
[person release]; // and here
A message sent to a nil
object is perfectly acceptable in Objective-C, it's treated as a no-op. There is no way to flag it as an error because it's not an error, in fact it can be a very useful feature of the language.
From the docs:
Sending Messages to nil
In Objective-C, it is valid to send a message to nil—it simply has no effect at runtime. There are several patterns in Cocoa that take advantage of this fact. The value returned from a message to nil may also be valid:
If the method returns an object, then a message sent to
nil
returns0
(nil
), for example:
Person *motherInLaw = [[aPerson spouse] mother];
If
aPerson
’sspouse
isnil
, thenmother
is sent tonil
and the method returnsnil
.If the method returns any pointer type, any integer scalar of size less than or equal to
sizeof(void*)
, afloat
, adouble
, along double
, or along long
, then a message sent tonil
returns0
.If the method returns a
struct
, as defined by the Mac OS X ABI Function Call Guide to be returned in registers, then a message sent tonil
returns0.0
for every field in the data structure. Otherstruct
data types will not be filled with zeros.If the method returns anything other than the aforementioned value types the return value of a message sent to nil is undefined.