Return nil;

Discussion in 'iOS Programming' started by larswik, Apr 27, 2012.

  1. larswik macrumors 68000

    Joined:
    Sep 8, 2006
    #1
    Quick question about nil. I have this code to check for a file and if it exists it returns it. In the IF statement I return the file if it exists. But I am getting a warning if I do not have a return at the end of this Method "Control may reach end of non-void function"

    Code:
    -(NSDictionary *)readInGearDict{
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:[self filePath:@"masterGearList.plist"]]) {
            NSDictionary *gearDict = [[NSDictionary alloc] initWithContentsOfFile:[self filePath:@"masterGearList.plist"]];
           [COLOR="Red"] return gearDict;[/COLOR]
        }
        [COLOR="Red"]return nil;[/COLOR]
    }
    I thought I would add a "return nil" if it can not locate the file. Is this the best way of doing it to get rid of the warning error?
     
  2. xStep macrumors 68000

    Joined:
    Jan 28, 2003
    Location:
    Less lost in L.A.
    #2
    When possible I try to have only one return at the end of the method or function. In simple cases as you demonstrated I'd change it to look like the following. Immediately at the beginning of the method I set the return variable to nil for objects and likely zero for numbers.

    Code:
    -(NSDictionary *)readInGearDict{
        NSDictionary *gearDict = nil;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:[self filePath:@"masterGearList.plist"]]) {
            gearDict = [[NSDictionary alloc] initWithContentsOfFile:[self filePath:@"masterGearList.plist"]];
        }
        return gearDict;
    }
    
    I'm working on some messy code right now that has many early returns. I don't like it and may yet figure out how to simplify it to one return at the end. Anyway, in this complicated case, I return nil at the bottom because if the code drops through to there, there is nothing to return. I'm returning an NSError otherwise.
     
  3. larswik thread starter macrumors 68000

    Joined:
    Sep 8, 2006
    #3
    Ahhh, Smart.... Assign it to nil first so it has that value and then Then change that value if the if statement returns a FALSE.

    Less returns sounds like a better approach.

    Thanks!
     
  4. iosdev macrumors newbie

    Joined:
    May 4, 2012
    #4
    Sorry, maybe spamming a little, but maybe

    Code:
    gearDict = [[[NSDictionary alloc] initWithContentsOfFile:[self filePath:@"masterGearList.plist"]] autorelease];
    ?
     

Share This Page