I need to use a scratch effect for my game. here is an example code years ago.
https://github.com/oyiptong/CGScratch
It works just fine, but when i use it together with navigation controller, it crashes.
My project uses ARC, i flag the file as -fno-objc-arc. Here is the source code:
https://github.com/lifesaglitch/ScratchWithError
it crashes when i push the view controller, then pop, then reenter.
Edit:
When you convert all to arc, and flag the view controller that uses the scratch view as -fno-objc-arc, it works. But when you flag the scratch view as -fno-objc-arc instead, it crashes again. My project uses arc and i dont think i can convert my own view controller to be -fno-objc-arc.
Edit 2:
I modify the initialization code to:
scratchable = CGImageRetain([UIImage imageNamed:@"scratchable.jpg"].CGImage);
it does not crash anymore, but there's a memory leak. and CGImageRelease did get called once in dealloc method.
Use CGImageCreateCopy
.
The reason for this is that you send a release to your CGImageRef
at your dealloc
, but if you inspect the actual CGImage
object you'll see that it points to the same memory address each time (I guess it's part of Apple's optimizations, so it's just like you would have a static UIImage
object and reference its CGImage
).
So in your initWithFrame:
you should get your scratchable like this:
UIImage *sci = [UIImage imageNamed:@"scratchable.jpg"]; // This guy is always the same
scratchable = CGImageCreateCopy(sci.CGImage);
PS: You had an actual leak with pixels
, so you also need a CFRelease(pixels);
I tested, analyzed and measured the code and it seems to be OK now.
Here is also a link to the fixed project (I've also put a navigation controller and a button to push/pop) - and uses ARC of course.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With