category on UIColor

Discussion in 'iOS Programming' started by North Bronson, Aug 5, 2009.

  1. North Bronson macrumors 6502

    Joined:
    Oct 31, 2007
    Location:
    San José
    #1
    I haven't used too many class methods before, but I found myself needing a custom color for my app.

    I was using an instance variable for the color, but I thought about just using using a category on UIColor. Would the new method really be just as simple as:

    Code:
    + (UIColor *)customColor
    {
        UIColor *color = [UIColor colorWithRed: 0.36 green: 0.24 blue: 0.36 alpha: 1.000];
        
        return color;
    }
    Hope that's not too lame of a question. I don't have much experience with class methods or categories.
     
  2. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #2
    Yes it's as simple as that although you need a header file also. This is how I do it:

    Code:
    // UIColor+Additions.h
    @interface UIColor (TableViewAddition)
    
    +(UIColor*)tangerine;
    
    @end
    
    @implementation UIColor (TableViewAddition)
    
    // UIColor+Additions.m
    // orange, from the crayons in IB
    +(UIColor*)tangerine
    {
    	static UIColor*	color = nil;
    	if (! color)	color = [[UIColor alloc] initWithRed:255.0f/255.0f green:128.0f/255.0f blue:0.0f/255.0f alpha:1.0f];
    	return color;
    }
    
    @end
    
     
  3. North Bronson thread starter macrumors 6502

    Joined:
    Oct 31, 2007
    Location:
    San José
    #3
    Cool. Thanks for the help. A couple of questions:

    where is the returned color released?

    Also, what is the significance of declaring a static UIColor instance? I've declared static C types like ints and floats, but I don't have too much experience declaring a pointer to a UIKit object as static.
     
  4. PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #4
    The returned color object is never released. The memory management rules say that an object is managed by the object that creates it. In code like this

    the color object isn't supposed to be released by the calling code. The usual assumption is that the object is autoreleased but that isn't a requirement of the memory management rules.

    The static keyword in this case generates a kind of global variable. This is exactly the same as in C. So in my implementation there will only ever be a single copy of the tangerine color object, no matter how many times you call that method. It will create the object the first time that the method is called and it will never be released. Your implementation will create color objects every time the method is called. Both are correct ways of doing this.
     

Share This Page