I have a NSDictionary that might be getting set inside a loop. At the end of the loop I want to find out if the dictionary has been defined. Here is an example:
NSDictionary *myDict;
for (int i=0; i < 100; i++){
if (thisCondition){
myDict = [NSDictionary dictionaryWithObjectsAndKeys:etc, nil];
}
}
if (myDict) {
[self doSomething];
}
Unfortunately, the test of myDict passes every time, whether myDict has been alloc'ed or not. Trying to pass any methods to myDict, like [myDict count], give a exc_bad_access because it has not been alloc'ed. So it is kind of a no man's land.
Is there a way to accomplish this? I realize I could switch to a NSMutableDictionary, define it, add to it in the loop, and test for a count, but that is not my preference.
First, make sure you initialize your pointer to nil:
NSDictionary *myDict = nil;
otherwise, your check for a valid pointer may not work.