drawRect: inside UIView category

I'm trying to do a UIView category for drawing inside drawRect: method without subclassing. To do this, I created a block to simplify this task.

Here's the code:


#import <UIKit/UIKit.h>

// DrawRect block
typedef void(^DrawRectBlock)(UIView *drawRectView, CGRect rect);

@interface UIView (DrawRectBlock)

- (void)drawInside:(DrawRectBlock)block;



#import "UIView+DrawRectBlock.h"
#import <objc/runtime.h>

@interface UIView ()

#pragma mark - Private properties
@property DrawRectBlock drawBlock;


@implementation UIView (DrawRectBlock)

- (void)drawInside:(DrawRectBlock)block {
    if ((self.drawBlock = [block copy])) {
        [self setNeedsDisplay];

- (void)drawRect:(CGRect)rect {
    if (self.drawBlock) {
        self.drawBlock(self, rect);

- (void)dealloc {
    self.drawBlock = nil;

#pragma mark - Others
- (void)setDrawBlock:(DrawRectBlock)drawBlock {
    objc_setAssociatedObject(self, @"block", drawBlock, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

- (DrawRectBlock)drawBlock {
    return objc_getAssociatedObject(self, @"block");


Finally, I call block as follows:

[_testView drawInside:^(UIView *drawRectView, CGRect rect) {


        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
        CGContextSetLineWidth(context, 5.0);
        CGContextMoveToPoint(context, 0.0, 0.0); //start at this point
        CGContextAddLineToPoint(context, 100.0, 100.0); //draw to this point


But "drawRect:" is never called. Any idea?



Finally I made a mix of subclass and category and works great! https://github.com/mhergon/SimpleBlockDrawing

Need Your Help

c++ data alignment /member order & inheritance

c++ inheritance alignment

How do data members get aligned / ordered if inheritance / multiple inheritance is used? Is this compiler specific?

Real-time Server Status and Information

php node.js webserver dashboard

Last week, I found an admin panel on WrapBootstrap which contains a Dashboard page. This page was awesome because it was containing some server informations about the load and the status.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.