View Full Version : Error in getting item from array

Jul 28, 2008, 08:09 PM
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!!


Jul 29, 2008, 07:33 AM
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...

Ron C
Jul 29, 2008, 09:35 AM
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:

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:

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;