hqt
hqt

Reputation: 30284

UIGraphicsGetCurrentContext(): Should we put CGContext as function parameter

I'm using Core Graphic library for drawing on UIView under method drawRect. As we know, under this method, we firstly get context by:

- (void)drawRect:(CGRect)rect {
   CGContextRef context = UIGraphicsGetCurrentContext();
}

I often use helper method for drawing. So, in helper method, should I put this context as parameter. For example:

- drawCircle:(CGContextRef)context center:(int)center radius:(int)radius {
// drawing here
} 

Or we can get context variable later in helper function:

- drawCircle: center:(int)center radius:(int)radius {
CGContextRef context = UIGraphicsGetCurrentContext();
// drawing here
}

I have tested and often don't see any problems. But I'm afraid, when I'm calling another method, something changes and UIGraphicsGetCurrentContext() will return different context variable. So is it safe to do in second way ? Because it will make my code clearer. And if wrong, please tell me will be wrong under what circumstance ?

Thanks :)

Upvotes: 1

Views: 1129

Answers (1)

TenaciousJay
TenaciousJay

Reputation: 6880

Good question. I noticed in the documentation for UIGraphicsGetCurrentContext it says:

The current graphics context is nil by default. Prior to calling its drawRect: method, view objects push a valid context onto the stack, making it current. If you are not using a UIView object to do your drawing, however, you must push a valid context onto the stack manually using the UIGraphicsPushContext function.

In iOS 4 and later, you may call this function from any thread of your app.

It sounds like that last sentence is implying this function is thread safe, and generally it seems like with threads you're worried that if you access the same function or properties in different places you might be accessing different things or they might not be syncing correctly so you could possibly be getting different info back from two different places.

I would assume that if it implies that this function is thread safe that it shouldn't matter if you access this from a different function as it should give you the same result, especially if you're not even using threads, so maybe this is more a matter of preference?

That said, in the 1st paragraph of that quote the second sentence mentions pushing a valid context onto the stack manually. If you code drawCircle where you pass in a context it seems like you have more flexibility because you can pass different contexts (if for some reason that was helpful) but if you hard code you can only ever use the default context returned by UIGraphicsGetCurrentContext().

Here's a link to the docs: UIGraphicsGetCurrentContext Documentation

Upvotes: 2

Related Questions