Graphics Programs Reference
In-Depth Information
Consider solving the same human-to-robot response problem with an array as the collec-
tion object. One approach would be to store every response in an ordered array. With this
approach, you would have to remember the index of every response by assigning a numer-
ic value to each facial expression. If you added a new expression-response pair, you'd
have to recompute the indices of each response. At some point early in your programming
career, you've probably done something like that:
int smileIndex = 0;
int scowlIndex = 1;
RobotResponses responses[2] = { "wink", "scream"};
if ([human isSmiling])
response = responses[smileIndex];
else if ([human isScowling])
response = responses[scowlIndex];
Another approach would be to store an object that held both the facial expression and the
response in an array. When the human made a facial expression, you would search the list
for the appropriate response.
for (ExpressionResponsePair *p in allResponses) {
if ([p expression] == [human facialExpression])
response = [p response];
}
Both of these approaches are inefficient and clumsy. A dictionary makes this lookup pro-
cess a lot faster and easier to understand:
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[dictionary setValue:@"wink" forKey:@"smile"];
response = [dictionary objectForKey:[human facialExpression]];
When using a dictionary, there can only be one object for each key. If you add an object to
a dictionary with a key that matches the key of an object already present in the dictionary,
the earlier object is removed. If you need to store multiple objects under one key, you can
put them in an array and add the array to the dictionary as the value.
Finally, note that a dictionary's memory management is like that of an array. Whenever
you add an object to a dictionary, the dictionary owns it, and whenever you remove an ob-
ject from a dictionary, the dictionary releases its ownership.
Search WWH ::




Custom Search