North Bronson

macrumors 6502
Original poster
Oct 31, 2007
395
1
San José
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.
 

PhoneyDeveloper

macrumors 68040
Sep 2, 2008
3,114
93
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
 
Comment

North Bronson

macrumors 6502
Original poster
Oct 31, 2007
395
1
San José
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.
 
Comment

PhoneyDeveloper

macrumors 68040
Sep 2, 2008
3,114
93
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

myview.backgroundColor = [UIColor tangerine];

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.
 
Comment
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.