Question

I am using [UIColor colorWithPatternImage:] and was expecting it to retain the image passed in. When I nil the image that is passed in, it is deallocated and any attempt to draw with the color results in a crash. Is this expected behavior or a bug?

// MyCustomUIImage is a sub-class with it's own custom data provider
UIImage* encodedImage = [[MyCustomUIImage alloc] initWithContentsOfFile:fileName];
UIColor* color = [UIColor colorWithPatternImage:encodedImage];

// color is then assigned to a singleton so it is never deallocated
// ... later ...

CGContextSetLineCap(ctx, kCGLineCapRound);
CGContextSetLineJoin(ctx, kCGLineJoinRound);
CGContextSetInterpolationQuality(ctx, kCGInterpolationNone);
CGContextSetMiterLimit(ctx, 0.1f);
CGContextSetShouldAntialias(ctx, YES);
CGContextSetAllowsAntialiasing(ctx, YES);
CGContextAddPath(ctx, self.path);
CGContextSetLineWidth(ctx, width);
CGContextSetStrokeColorWithColor(ctx, color.CGColor);
CGContextSetFillColorWithColor(ctx, NULL);
if (self.glowAmount > 0.0f && self.glowColor.alpha > 0.0f)
{
    CGContextSetShadowWithColor(ctx, CGSizeZero, self.glowAmount, self.glowColor.CGColor);
}
CGContextSetBlendMode(ctx, blendMode);

// *** CRASHES HERE ***
CGContextDrawPath(ctx, kCGPathStroke);
Was it helpful?

Solution 3

UIColor does retain the UIImage, but it will not retain the data provider. I was releasing the data provider and that was causing the crash.

OTHER TIPS

If you use ARC, ARC may think your "color" is never used again , so it will destroy it automatically. It will not appear everytime. It will maybe appear when low memory.

you can fix it like this:

UIColor* __autoreleasing color = [UIColor colorWithPatternImage:encodedImage];

UIColor's methods colorWithPatternImage and initWithPatternImage. It turns out these two methods use a lot of memory, way more than any one would expect.

instead of that use [UIColor initWithRed:0.25 green:0.25 blue:0.25 alpha:1]; or some how use UIImageView behind your current layer.

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