正确使用目标C中的内存管理

时间:2014-06-24 08:18:47

标签: objective-c

我在Objc中第一次使用低级API,现在我必须控制内存管理,然后我会在更高级别的apis上。所以我阅读了Apple编写的高级和基本内存管理指南。但是现在在实践中我并不是百分百确定,所以我做了一个小例子来看看这是否可行。我的代码:

- (void)drawRect:(CGRect)rect
    {
        [super drawRect:rect];

        //Method contains the word "Get" so make sure it won't release so retain it
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextRetain(context);

        //No retain needed since method contains word "Create"
        CFStringRef string = CFStringCreateWithCString(kCFAllocatorDefault, "Supppp....", kCFStringEncodingUTF8);
        CFShowStr(string);
        CFRelease(string);

        CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
        CGContextSetLineWidth(context, 6.0);
        CGContextStrokeRoundedRect(context, CGRectInset(rect, 5 , 5), 3);

        //Clean up
        CGContextRelease(context);
    }

void CGContextRoundedRect(CGContextRef context, CGRect rect, CGFloat radius, CGPathDrawingMode mode) {
        CGFloat minx = CGRectGetMinX(rect), midx = CGRectGetMidX(rect), maxx = CGRectGetMaxX(rect);
        CGFloat miny = CGRectGetMinY(rect), midy = CGRectGetMidY(rect), maxy = CGRectGetMaxY(rect);
        CGContextRetain(context);

        CGContextMoveToPoint(context, minx, midy);
        CGContextAddArcToPoint(context, minx, miny, midx, miny, radius);
        CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius);
        CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius);
        CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius);
        CGContextClosePath(context);
        CGContextDrawPath(context, mode);

        //Cleanup
        CGContextRelease(context);
    }

    void CGContextFillRoundedRect(CGContextRef context, CGRect rect, CGFloat radius) {
        CGContextRetain(context);
        CGContextRoundedRect(context, rect, radius, kCGPathFill);
        CGContextRelease(context);
    }

void CGContextStrokeRoundedRect(CGContextRef context, CGRect rect, CGFloat radius) {
        CGContextRetain(context);
        CGContextRoundedRect(context, rect, radius, kCGPathStroke);
        CGContextRelease(context);
    } 

这是对的吗?

0 个答案:

没有答案