Error in getting item from array

Discussion in 'iPhone/iPad Programming' started by DSchwartz88, Jul 28, 2008.

  1. macrumors 6502

    Joined:
    May 18, 2006
    #1
    Hey All,

    Im having an issue with my program. The following function gets information needed for an HTTPRequest, however, it does not grab the information.

    - (NSDictionary*)getSelNewsItem {
    NSIndexPath *ip = [postsTable indexPathForSelectedRow];

    if(ip == nil) return nil;
    else {
    return [news objectAtIndex:ip.row];
    }

    The line that is not working is:

    NSIndexPath *ip = [postsTable indexPathForSelectedRow];


    for some reason when it goes to grab that it comes back nil, however in the same .m file i use postsTable for other functions and the data comes back fine. Please help!!

    Thanks,
    Daniel
     
  2. macrumors member

    Joined:
    May 24, 2003
    #2
    For starters, I suggest you lose the semicolon at the end of :

    if(ip == nil) return nil;

    Otherwise the else statement will never be reached...
     
  3. macrumors member

    Joined:
    Jul 18, 2008
    Location:
    Chicago-area
    #3
    Yeah, I'm not particularly thrilled with bare statements following if or else because they confuse the reader. My recommendation is to wrap the statement in braces.

    Further, I would re-order the test (that is, make the positive one the first one). I'm not much of a Obj-C programmer yet, so if I were to write it like a C/C++ programmer I'd use something more like:

    Code:
    if (ip != nil) { // this would be "if (ip) {" in my C/C++ code
        return [news objectAtIndex:ip.row]; 
    } else {
        return nil;
    }
    Another option is to step through it in the debugger and see what happens. If you're going to do that, I like adding in throw-away locals to both add handy breakpoint places along with easily showing intermediate values. There my recommendation is more like this:

    Code:
    if (ip != nil) { // this would typically be "if (ip) {" in my C/C++ code
        // not sure the type of row or the result of this call, so let's call them
        // "int" and "Thing" respectively.
        int _row = ip.row;
        Thing *_result = [news objectAtIndex: ip.row];
        return _result;
        // Leave this code here, we may want to return to the simpler, more
        // direct version once we're happy with it working as expected.
        // return [news objectAtIndex:ip.row]; 
    } else {
        return nil;
    }
     

Share This Page