Search code examples
iosiphonenslogcorrupt

iphone nslog corrupted data


I am having a weird problem with variable values. This is the code (it is part of a class method):

MyAppDelegate *pDelegate = [[UIApplication sharedApplication] delegate];
SomeDictionaryData *appData = [pDelegate.theData retain];
NSLog(@"my instance var: %@",cardIndex); // outputs "my instance var: 4"
NSDictionary *currentCard = [[NSDictionary alloc] initWithDictionary:[appData.cards objectAtIndex:cardIndex]];;
// the above line breaks the app
[currentCard release];
[appData release];

I am using the debugger with the objc_exception_throw breakpoint. The input received by objectAtIndex in there shows as having value = 13760640. The cards attribute of appData is an NSArray and it clearly does not have ten million + items so I get an out of bounds error. I tried casting with (int)cardIndex with no better results. Weird thing is a similar code in some other class works fine.

This is some data I want to use throughout my app so I have a Model class that gets initialized in the AppDelegate as theData and then is accesed by different ViewControllers. This error shows up after one successful access on some other ViewController (that one also does retain/release).

Any help will be appreciated.


Solution

  • Use [cardIndex unsignedIntValue] for the objectAtIndex: line.

    You cannot give objectAtIndex: a pointer because it expects an unsigned integer.

    For example:

    NSDictionary *currentCard = [[NSDictionary alloc] initWithDictionary:[appData.cards objectAtIndex:[cardIndex unsignedIntValue]]];
    

    EDIT:

    It sounds like cardIndex is an int but somewhere along the lines it is being set as an NSNumber instance. As a hack, use [(id)cardIndex unsignedIntValue]. If this works, then it means you are using the wrong type for cardIndex (it should be NSNumber, not int).