Is there a convenient way to have two different “nil-like” possible return values from a method?

The method in question (actually a polymorphically-implemented family of recursive search methods) returns a pointer to a certain type of object. I had been returning nil in cases of failure. Now I want to have two different kinds of failure. What is the easiest way to implement that?

Answers


The best way to do this is to keep the return nil;, but take an error pointer as one of the function arguments. This way, you can send in an error, and check it for a value afterward to see what happened. Your function will still run, but you'll have some control over what gets returned.

As an example, here's some code I use for saving a managedObjectContext:

NSManagedObjectContext *moc = [self managedObjectContext];

NSError *error;
if (![moc save:&error]) {
    NSString *description = [error localizeDescription];
            NSInteger code = [error code];
}

I've tweaked the inside of the block to show a couple of the ways to pull info out of an error. For you, it'd probably be best to use simple error codes to distinguish between different nil values.

Here's a code example (though probably not the best way, as you'll have to duplicate code to interpret the error messages):

-(id) functionCall:(NSError *)error {
    ...
    if (nilCondition) {

        if (firstNilCondition) {
            [error setCode:1];
        }
        if (firstNilCondition) {
            [error setCode:2];
        }

        return nil;
    }
}

Need Your Help

Learning C# ASAP to get started with ASP.NET?

c# asp.net

I have experience writing web apps in Django; scripting in Python; playing with PHP and I understand Object Oriented Programming. I need to get started ASAP with C# in order to start learning and u...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.