Question

I've been programming since 2 months (so I'm quite a new) and i'm currently learning how to draw graphics for an iphone app but i need clarification on CGContext. To create the current context we useCGContextRef currentContext=UIGraphicsGetCurrentContext(), here if I understand well(and please correct me if I'm wrong),UIGraphicsGetCurrentContext() create the current context but we assign it to a pointer of type CGContexRef. Is the current context a object allocated memory on the heap or is it just a type of variable on the stack? I know we use pointer to work with the same data and avoid copying big memory blocks (right ?) but what is really a CGContext, an object, a struct or whatever?

Was it helpful?

Solution 3

The point of these opaque types is that you don't need to know and don't need to care. Apple could change its internals with every release and we wouldn't know (and don't need to). Usually, FooRef types are pointers to something. Right now, it's defined as:

typedef struct CGContext *CGContextRef;

But what struct CGContext looks like, we don't know. It looks like it's really a CoreFoundation (and maybe Objective-C) object since there are the usual retain/release functions:

CGContextRef CGContextRetain (CGContextRef c);
void CGContextRelease (CGContextRef c);

The usual CoreFoundation memory naming patterns apply: you don't need to release a CGContextRef unless it was returned by a function that contains the words Create or Copy.

OTHER TIPS

Short answer: CGContextRef is a pointer to a CGContext, which is a struct.

A CGContext is technically a struct, but it is conceptually an object, but in C, not Objective-C. The Core frameworks are object-oriented C frameworks.

Also, @dandan78's advice is good to help find out what things are.

It's an object disguised as an opaque C pointer. If you cast it to id it will behave like any other object (it wont need explicit retaining/releasing under ARC, can be added to collections, etc). The CGContext API requires it to be cast as a CGContextRef though.

The same goes for all of the Core Foundation SomethingRef types. Some, like CFArray can be safely cast to their equivalent Cocoa type (like NSArray). In general, it isn't that useful. It made it easier for people migrate their old Carbon-based code to Cocoa back when people still used Carbon.

Worth remembering that you can do po on a CFType in the debugger.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top