There is no particular meaning, but there are two things in common.
The first is related to databases, conservation levels, graphics, and such animals, where you need the concept of "scope", "connection" or "state". For example, when saving data to a database, you usually need to open the database, and then save some DB descriptor, which you will refer to in subsequent operations. There can be many different compounds and, therefore, many different “pens”. In other words, there can be many database contexts. The same goes for OpenGL.
Context is also often used in various callback and selector APIs. Here is just some piece of data that you would like to receive when the callback happens, or the selector gets annoyed. A common use case is when you sign up several times and should report all of these cases:
// In one part of code not far away. [anObject subscribeToEvent:NSObjectEventFoo withContext:@"one"]; // Somewhere else. [anObject subscribeToEvent:NSObjectEventFoo withContext:@"two"]; // And when the callback happens: - (void) eventFooHappenedInContext: (id) context { if ([context isEqual:@"one"]) { /* something */ } if ([context isEqual:@"two"]) { /* something else */ } }
Context is also used in the sort API, for example, in the NSArray that you mentioned. If, for example, you wanted to sort objects according to some weight stored in NSDictionary , you could use a context to pass weights:
NSInteger weightSort(id obj1, id obj2, void *context) { NSDictionary weights = (NSDictionary*) context; const int weight1 = [[weights objectForKey:obj1] intValue]; const int weight2 = [[weights objectForKey:obj2] intValue]; if (weight1 < weight2) return NSOrderedAscending; else if (weight1 > weight2) return NSOrderedDescending; else return NSOrderedSame; }
(This is a little far-fetched, but I think you get the point.)
It seemed interesting to me that context is many times just a bad solution for closures that is missing / missing in the language. Since with closure you can simply pass in a separate callback handler, for example, in JavaScript:
anObject.subscribeToEvent(eventFoo, function() { }); anObject.subscribeToEvent(eventFoo, function() { });
This will often be more elegant than differentiating use cases in a callback. Now you can do something similar in Objective-C with blocks (see Mike Ashe's tutorial ).