开发者

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?


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;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜