If you work with a designer on an iOS or OS X project, it’s likely that you will be given color information as 8-bit per channel integer RGBA values. In this format, white is represented as (red:255, green:255, blue:255, alpha:255) and black is represented as (red:0, green:0, blue:0, alpha:255). The fourth channel, alpha, represents the opacity of the color. An alpha of 0 is fully transparent and an alpha of 255 is fully opaque.
Unfortunately, UIColor does not provide convenience class methods or initializers for working with color information in 8-bit per channel integer RGBA format. This is sort of weird. Apple should add these missing class methods and initializers. When was the last time someone gave you a color in the form (r:0.875674, g:0.938457, b: 0.234234)?
It’s simple enough to fill in where Apple left off by building an extension to UIColor that adds the missing class methods (I’ll leave the initializers up to you; I don’t need them.)
Here’s the .h file:
//
//  UIColor+Extensions.h
//
//  No copyright. No rights reserved.
//
#import <UIKit/UIKit.h>
// UIColor (Extensions) interface.
@interface UIColor (Extensions)
/**
 * Creates and returns a color object using the specified RGB component values.
 *
 * @param r The red component of the color object, specified as a value from 0 to 255.
 * @param g The green component of the color object, specified as a value from 0 to 255.
 * @param b The blue component of the color object, specified as a value from 0 to 255.
 * @return The color object. The color information represented by this object is in the device RGB colorspace.
 */
+ (UIColor *)colorWithR:(UInt8)r g:(UInt8)g b:(UInt8)b;
/**
 * Creates and returns a color object using the specified RGBA component values.
 *
 * @param r The red component of the color object, specified as a value from 0 to 255.
 * @param g The green component of the color object, specified as a value from 0 to 255.
 * @param b The blue component of the color object, specified as a value from 0 to 255.
 * @param a The alpha component of the color object, specified as a value from 0 to 255.
 * @return The color object. The color information represented by this object is in the device RGB colorspace.
 */
+ (UIColor *)colorWithR:(UInt8)r g:(UInt8)g b:(UInt8)b a:(UInt8)a;
@end
Here’s the .m file:
//
//  UIColor+Extensions.m
//
//  No copyright. No rights reserved.
//
#import "UIColor+Extensions.h"
// UIColor (Extensions) implementation.
@implementation UIColor (Extensions)
/**
 * Creates and returns a opaque color object using the specified RGB component values.
 *
 * @param r The red component of the color object, specified as a value from 0 to 255.
 * @param g The green component of the color object, specified as a value from 0 to 255.
 * @param b The blue component of the color object, specified as a value from 0 to 255.
 * @return The color object. The color information represented by this object is in the device RGB colorspace.
 */
+ (UIColor *)colorWithR:(UInt8)r g:(UInt8)g b:(UInt8)b
{
    return [UIColor colorWithRed:(CGFloat)r / (CGFloat)255.0
                           green:(CGFloat)g / (CGFloat)255.0
                            blue:(CGFloat)b / (CGFloat)255.0
                           alpha:(CGFloat)1.0];
}
/**
 * Creates and returns a color object using the specified RGBA component values.
 *
 * @param r The red component of the color object, specified as a value from 0 to 255.
 * @param g The green component of the color object, specified as a value from 0 to 255.
 * @param b The blue component of the color object, specified as a value from 0 to 255.
 * @param a The alpha component of the color object, specified as a value from 0 to 255.
 * @return The color object. The color information represented by this object is in the device RGB colorspace.
 */
+ (UIColor *)colorWithR:(UInt8)r g:(UInt8)g b:(UInt8)b a:(UInt8)a
{
    return [UIColor colorWithRed:(CGFloat)r / (CGFloat)255.0
                           green:(CGFloat)g / (CGFloat)255.0
                            blue:(CGFloat)b / (CGFloat)255.0
                           alpha:(CGFloat)a / (CGFloat)255.0];
}
@end
Happy coding!
Brian
 
I recently wanted to measure the speed of something I was doing in an iOS application. I searched for the best way to do this and found two basic approaches.
The first approach is to use date arithmetic. Something like:
NSDate * start = [[NSDate allocinit];
[NSThread sleepForTimeInterval:1.0]; // Thing to be measured.
NSDate * stop = [[NSDate allocinit];
NSLog(@”Thing took %f sec”, [stop timeIntervalSinceDate:start]);
Another way to write the same code would be:
NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];
[NSThread sleepForTimeInterval:1.0]; // Thing to be measured.
NSTimeInterval stop = [NSDate timeIntervalSinceReferenceDate];
NSLog(@”Thing took %f sec”, stop - start);
The problem with the date arithmetic approach is that it uses NSTimeInterval. NSTimeInterval expresses time in seconds with at best “sub-millisecond resolution”, whatever that is. This means that unless you are timing things that execute in many tens, hundreds, or thousands of milliseconds, you won’t get very useful measurements using this approach.
The next approach is to use mach_absolute_time, which offers the precision I am looking for. Apple has a Technical Q&A on this approach: QA1398. The problem with QA1398 is that it shows you how to perform the measurement but not how to build a reusable performance timer.
I set out to write a performance timer in Objective-C that would do the job in a simple and reusable way. The class is called PerfTimer.
The project page can be found on github.com: https://github.com/softwarenerd/PerfTimer
Here’s the PerfTimer.h file:
//
//  PerfTimer.h
//
//  No copyright. No rights reserved.
//
#import <Foundation/Foundation.h>
// PerfTimer interface.
@interface PerfTimer : NSObject
// Starts or restarts the perf timer.
- (void)start;
// Captures the perf timer.
- (void)capture;
// Returns the elapsed time in nanoseconds of the last capture.
- (UInt64)nsElapsed;
// Returns the elapsed time in milliseconds of the last capture.
- (UInt32)msElapsed;
// Returns a string representation of the last capture.
- (NSString *)stringWithElapsedTime;
@end
Here’s the PerfTimer.m file:
//
//  PerfTimer.m
//
//  No copyright. No rights reserved.
//
#import “PerfTimer.h”
#include <mach/mach.h>
#include <mach/mach_time.h>
// PerfTimer implementation.
@implementation PerfTimer
{
@private
    // The absolute to nanosecond conversion factor.
    volatile long double factor_;
    
    // The started absolute time.
    volatile UInt64 started_;
   
    // The capture absolute time.
    volatile UInt64 capture_;
}
// Class initializer.
- (id)init
{
    // Initialize superclass.
    self = [super init];
    
    // Handle errors.
    if (!self)
    {
        return nil;
    }
           
    // Precalculate the absolute time to nanosecond conversion factor as it
    // only needs to be done once.
    mach_timebase_info_data_t info;
    mach_timebase_info(&info);
    factor_ = ((long double)info.numer) / ((long double)info.denom);
           
    // Done.
    return self;
}
// Starts or restarts the perf timer.
- (void)start;
{
    started_ = mach_absolute_time();
    capture_ = 0ULL;
}
// Captures the perf timer.
- (void)capture
{
    // Get the capture time.
    UInt64 capture = mach_absolute_time();
    
    // If the timer was started, set capture time; otherwise, ignore the call.
    if (started_)
    {
        capture_ = capture;
    }    
}
// Returns the elapsed time in nanoseconds.
- (UInt64)nsElapsed
{
    if (!started_ || !capture_)
    {
        return 0LL;
    }
    return (UInt64)roundl((long double)(capture_ - started_) * factor_);
}
// Returns the elapsed time in milliseconds.
- (UInt32)msElapsed
{
    if (!started_ || !capture_)
    {
        return 0LL;
    }
    return (UInt32)roundl((long double)(capture_ - started_) * factor_ / 1000000.0L);
}
// Returns a string containing a representation of the elapsed time.
- (NSString *)stringWithElapsedTime
{
    // Allocate a number formatter and initialize it with the decimal style. 
    NSNumberFormatter * formatter = [[NSNumberFormatter allocinit];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    // Obtain the elapsed ns.
    UInt64 nsElapsed = [self nsElapsed];
    // Format the elapsed ns. This will always be returned.
    NSString * nsElapsedString = [formatter stringFromNumber:[NSNumber numberWithLongLong:nsElapsed]];
    // If the elapsed ns is < 1 ms, just return the elapsed ns.
    if (nsElapsed < 1000000ULL)
    {
        return [NSString stringWithFormat:@"[%@ ns]“, nsElapsedString];
    }
    // Format the elapsed ms.
    NSString * msElapsedString = [formatter stringFromNumber:[NSNumber numberWithLong:[self msElapsed]]];
    
    // Done.
    return [NSString stringWithFormat:@"[%@ ms] [%@ ns]“, msElapsedString, nsElapsedString];
}
@end
Here’s an example of how to use it:
// Allocate and initialize the perf timer.
PerfTimer * perfTimer = [[PerfTimer allocinit];
// Measure sleeping 1/2 second.
[perfTimer start];
[NSThread sleepForTimeInterval:0.5];
[perfTimer capture];
NSLog(@"   Sleep 1/2 second: %@", [perfTimer stringWithElapsedTime]);
// Measure sleeping 1 second.
[perfTimer start];
[NSThread sleepForTimeInterval:1.0];
[perfTimer capture];
NSLog(@"     Sleep 1 second: %@", [perfTimer stringWithElapsedTime]);
// Measure sleeping 4.6 seconds.
[perfTimer start];
[NSThread sleepForTimeInterval:4.6];
[perfTimer capture];
NSLog(@"  Sleep 4.6 seconds: %@", [perfTimer stringWithElapsedTime]);
Here’s the output:
PerfTimer[15551:707]    Sleep 1/2 second: [501 ms] [500,621,412 ns]
PerfTimer[15551:707]      Sleep 1 second: [1,001 ms] [1,000,748,801 ns]
PerfTimer[15551:707]   Sleep 4.6 seconds: [4,601 ms] [4,601,025,431 ns]
One of the useful things about this class is that you can allocate one instance of it and use it over and over again to measure segments of your code by calling -start / -capture around the segments to be measured.
It’s also useful in cases where it will be called serially by different threads. An example of this would be allocating and starting a PerfTimer in the main part of a method and then subsequently calling capture on it in a block that is executed when an asynchronous operation completes.
Here’s an example:
// Allocate and initialize the perf timer.
PerfTimer * urlPerfTimer = [[PerfTimer allocinit];
// Allocate and initalize the URL request.
NSURLRequest * urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]
                                             cachePolicy:NSURLCacheStorageNotAllowed
                                         timeoutInterval:60.0];
// Perform the URL request asynchronously using an NSURLConnection.
[urlPerfTimer start];
[NSURLConnection sendAsynchronousRequest:urlRequest
                                   queue:_operationQueue
                       completionHandler:^(NSURLResponse * urlResponse, NSData * data, NSError * error)
 {
     if (!error)
     {
         [urlPerfTimer capture];
         NSLog(@"Google took: %@", [urlPerfTimer stringWithElapsedTime]); 
     }
 }];
The result of this was:
PerfTimer[15700:4003] Google took: [167 ms] [166,984,916 ns]
(Which, BTW, is damn fast!)
As it is, this class is useful when the overhead of passing the -start and -capture messages to an instance of it is inconsequential relative to the time it takes to perform the thing being measured. On my system, an empty -start -capture pair measures out at ~50 ns.
Here’s an example:
[perfTimer start];
[perfTimer capture];
NSLog(@"Empty start/capture: %@", [perfTimer stringWithElapsedTime]);
[perfTimer start];
[perfTimer capture];
NSLog(@"Empty start/capture: %@", [perfTimer stringWithElapsedTime]);
[perfTimer start];
[perfTimer capture];
NSLog(@"Empty start/capture: %@", [perfTimer stringWithElapsedTime]);
[perfTimer start];
[perfTimer capture];
NSLog(@"Empty start/capture: %@", [perfTimer stringWithElapsedTime]);
The output of this code is:
PerfTimer[19189:403] Empty start/capture: [45 ns]
PerfTimer[19189:403] Empty start/capture: [53 ns]
PerfTimer[19189:403] Empty start/capture: [55 ns]
PerfTimer[19189:403] Empty start/capture: [45 ns]
The overhead of passing -start and -capture messages to an instance of PerfTimer biases its results. Measuring this overhead and calibrating the results the class returns should improve its accuracy.
Happy coding!
Brian
 
It turns out that ecto is also full of bugs and totally useless. It looks like the only reliable way to author blog posts will be to use the built-in WordPress tools on the site.
Happy coding!
Brian
 

Code samples here are completely unlicensed. That means you are free to do anything you like with code you see here.

I include the following comment in the header of each source file: “No copyright. No rights reserved.”

Happy coding!

Brian

 

Syntax Formatter is now available on github. The project page can be found at: https://github.com/softwarenerd/SyntaxFormatter

This simple utility is an OS X program that converts code samples copied from Xcode to the clipboard into HTML that you can insert in blog postings, web pages, and so on.

To use it, select a code sample from Xcode and copy it to the clipboard.

Next, press the Process Clipboard toolbar item in Syntax Formatter (⌘-P) to process the sample. You will then see a preview of the sample HTML in the main window:

Finally, press the Copy HTML toolbar item in Syntax Formatter (⌘-C) to copy the processed HTML to your clipboard. This HTML can then be pasted into a blog posting, web page, or any other place you need it.

I’ve submitted Syntax Formatter to the Mac App Store. When it’s approved, I will be posting details on how to download and install it.

Happy coding!

Brian

 

Welcome to my new blog, objective-brian.com. This blog is about Objective-C, iOS, and OS X programming.

Blogging Software

The first order of business was to select a blog authoring tool for the Mac. I downloaded and tried out three tools: MarsEdit, Blogo, and ecto.

MarsEdit

My initial favorite was MarsEdit, but, it has a number of fatal flaws that ruled it out. The worst of these flaws is that when you switch from Rich Text to HTML editing to paste in a syntax highlighted code sample (more on this later), and then switch back to Rich Text editing, it significantly alters the HTML that was pasted. In particular, it removes &nbsp; entities, which totally screws up the indentation of code samples.

Blogo

I’m not sure what was going on with Blogo, but it wouldn’t run:

Blogo Dies

ecto

That left ecto. Lucky for me, ecto works, and, it’s actually a very nicely done piece of software. It has every feature I need, and, most importantly, it doesn’t alter the HTML of syntax highlighted code samples like MarsEdit. It also publishes posts a lot faster than MarsEdit.

Blogging With Sample Code

The next order of business was to sort out how to best publish sample code. The way sample code is formatted plays a big part in how effective a programming blog is. Plain code samples are difficult to read, which is why most programming blogs make use of some type of sample code formatting, including syntax highlighting. Since this is a WordPress blog, and there are a lot of WordPress syntax plugins available to do this, it seemed like this would be an easy problem to solve.

It wasn’t.

I installed and tested pretty much every syntax highlighter for WordPress and I didn’t like any of them. They were all broken in one way or another. After researching things and looking into how they work, it was pretty clear why: they rely on inferior parsing engines and incomplete language element definitions.

After thinking about this for a while it occurred to me that when I am working in Xcode and copy / paste code into TextEdit, the Xcode syntax highlighting is perfectly preserved:

XcodeCode.png

I did some research into why this works and it turns out that Xcode copies RTF text onto the clipboard that is formatted exactly like it appears in Xcode.

This is what I want for this blog! I want code samples in this blog to look exactly like they do in Xcode. I wrote my own tool to do this called XcodeSyntaxFormatter.

Here is the output:

//
//  main.m
//  XcodeSyntaxFormatter
//
//  No copyright. No rights reserved.
//
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
{
    return NSApplicationMain(argc, (const char **)argv);
}

I’m happy with the result.

I will be writing a post about XcodeSyntaxFormatter in the coming days and making it available on github to anyone who wants to use it, or, contribute to it in some way.

Well, that’s it for the first post.

Happy coding!

Brian

© 2012 Objective-Brian Suffusion theme by Sayontan Sinha