As others have said, the variable myarray contains a dictionary.
To explain fully:
In Objective-C, a variable that contains an object actually contains a pointer to that object. Think of it as an entry in your program’s rolodex.
The variable has a type, “pointer to array”. It points to an object that should be an array.
However, it is possible to lie to the compiler, and have the variable point to something that is not actually an array.
EDIT:
To continue the rolodex analogy, it’s as if you have an entry in your rolodex for a plumber, but the phone number (the pointer) is actually the phone number for a roofer. You call the number and start asking the person that answers about plumbing. The roofer doesn’t understand what you are talking about, and hangs up. (The conversation crashes.)
The phone number is the pointer, of the wrong type. The pointer of type plumber actually points to an instance of the roofer class, so bad things happen when you start sending plumber messages to the roofer.
Take this code for example:
- (void) typeCasting;
{
NSDictionary* aDict =
{
@"key1": @"value1",
@"key2": @"value2",
} // -1-
NSArray *anArray;
//The compiler throws an error here.
anArray1 = aDict; //-2-
//The compiler allows this due to typecasting.
anArray2 = (NSArray *) aDict; //-3-
//This code compiles but crashes at runtime.
NSString *aString = anArray2[0]; //-4-
//typecast back to dict
NSDictionary *anotherDict = (NSDictionary *) anArray2; //-5-
}
At the line marked -1-
above, we create a dictionary.
At -2-
we try to assign our dictionary to a new variable of type NSArray*
. The compiler complains, as it should. This is a programming error that the compiler prevents.
At -3-
, we commit the same error, but this time we add the (NSDictionary*)
typecast, which tells the compiler “Trust me, I know what I’m doing.” This is setting us up for runtime crashes later.
At -4-
we try to index into anArray2
, but it doesn’t really contain an array, it contains a dictionary. We crash.
My guess is that somewhere in your code, you have a line like -3-
where you cast a dictionary to an array, and set yourself up for your crash. The correct fix is to not do that in the first place. However, you could “band-aid” it after the fact by re-casting your myarray
back to a dictionary, as shown in -5-
above.
1
solved Accessing values from NSArray [duplicate]