I have this method that I inserted a object and it updates a view based on that object. However, when this object is nil it doesn't crash even when I am not being defensive.
- (void) updateWithObject:(NSObject *)obj {
// obj is nil so how can I access property with out a exception?
if ([(NSDictionary *)[obj property] valueForKey:@"KEY"]) {
//set object values
} else {
//set object values
}
}
That's just the way Objective-C works. To access properties or to call methods you send a message to an object. To do this the C function objc_msgSend is called with the object itself, the selector and all the other arguments that method takes. This does much more than just calling the method. First it checks if the receiver is nil. If it is it returns immediately with an result of nil (or zero or an empty struct). Otherwise it looks up the appropriate method for the selector and calls that if found. If not it enters the message forwarding machinery which sends this object some more messages to dynamically handle this unknown selector. This is all done without throwing exceptions or otherwise crashing. Only as the last resort forwardInvocation: is called whose default implementation in NSObject throws an exception and thus crashes. Before this the object had plenty chances of handling this message.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With