Logicsaurus Rex
Logicsaurus Rex

Reputation: 3192

Return something other than nil from a method sent to nil

This is probably impossible with a category, but just in case it is doable, I wanted to find out.

I wrote a category on NSString and I have a category method that parses a comma delimited string into an NSArray cleaning up extra commas and spaces, and trimming the ends... so more comprehensive than the built-in method of similar functionality. Here's the rub though... what if the string is nil? Is there any way I can return an initialized NSArray with 0 objects instead of returning nil?

The scenario would go something like this...

NSArray *parsed = [someString parseStringIntoArray];

... assume someString is nil. Can I somehow get an initialized array out of this?

Obviously there are ways to work AROUND this, but keeping it clean and succinct, and using the category method... is it possible?

Upvotes: 0

Views: 83

Answers (2)

Julian F. Weinert
Julian F. Weinert

Reputation: 7560

No. But yes, if you make some changes:

Since you call a instance method, this won't work. When you send a message to nil (aka call a method on a nil object) you will always get nil. This is the key concept of nil itself.

You can for example add a class method and in this class method, you can then test against nil and return an empty array instead:

+ (NSArray *)parseStringIntoArray:(NSString *)string {
    return [string componentsSeparatedByString:@","] ?: @[];
}

or you can simply use, what NSString has built in:

NSArray *parts = [@"foo,bar,la,le,lu" componentsSeparatedByString:@","] ?: @[];

EDIT

Upvotes: 2

jscs
jscs

Reputation: 64002

No, there's no way to return anything from a message sent to nil. That is baked into the very core of the runtime: objc_msgSend() is responsible for this behavior.

If the receiver is nil, objc_msgSend() resolves the expression to the appropriate 0 value for the return type of the method.

You will have to test for nil either before or after and change the value of the array manually.

(Incidentally, the fact that this is a category method is irrelevant.)

Upvotes: 1

Related Questions