Author Archives:

More about block pitfalls

Conrad Stoll tweeted me a great article he wrote about a complicated pitfall he ran into while working with NSBlockOperation.  Check out this great real-world example of retain cycles and how to resolve them:

More On The Whole “Learning to Code” Thing

Scott Hanselman wrote an excellent piece on the “learning to code” discussion that occurring (still) on sites like HackerNews.  I feel he gets closer to the point of Atwood’s original idea.  Maybe a different angle.  The point is that you should learn to code if you have a burning desire to and more importantly if you have a need to.

Bloomberg would do well to learn how the internet works, but coding is not necessarily a requirement.  Same goes for Congress — because they have to deal with and legislate technological issues.  If you own a sink you should learn a bit about plumbing to know how it works.  Water doesn’t simply materialize out of thin air and enter the faucet and it doesn’t just evaporate in the drain.  Just as plumbing is a means to have a running water system in your house.  Coding is likewise a skill to be used to create larger systems but it’s no more a solution to anything any more than plumbing (as a skill) is a solution to supplying water in your home..

The point — Coding in itself is not a solution.

To Code or Not To Code – That is the (stupid) question

There’s a lot talk this week around Jeff Atwood’s post on CodingHorror where he asks the populace at large to not learn to code.  I’m not sure of what to think of the numerous responses and comments on the web.  Perhaps it’s a matter of people being too caught up in their craft.  Perhaps it’s simply vogue to disagree with Jeff Atwood.  Regardless, 90% of the responses are missing Jeff Atwood’s point.

When all you have is a hammer . . .

You don’t have to look around and see that multiple systems are horribly broken: education, healthcare, government just to name a few.  Entrepreneurs everywhere are and should be chomping at the bit to fix these problems.  There’s a hell of business to be made on solving these problems successfully and safely.  Code is not the way.

These industries have no shortage code.  Government has more code than they know what to do with.  So does healthcare.  Much of it is probably bad.  Simply throwing more code at it shouldn’t be the answer, especially if it’s bad code.  Jeff Atwood makes the point that the world doesn’t need more bad code by bad coders.  He’s right.

What these industries need and what Jeff is really advocating is solutions.  Code should be the last thing we’re all thinking about when we’re trying to solve the enormous problems plaguing them.  Code will most certainly be a part of the solution, but only a means to that solution once the important decisions have been handled elsewhere.  Code itself is not the solution anymore than a hammer and nails are the solution to housing problems.

Code if you want to . . .

Code if you want to learn to code.  Code if you really want a deep understanding of how computer programs work.  But if you’re going to delve in learn it well and learn it right.  Don’t learn “just enough to be dangerous” as the adage goes.  If you’re an entrepreneur, learn to find and craft solutions.  Solutions are always more than just code.  Once you have a good solution to horrible problem there will be no shortage of great coders to work with you and take care of the hammers and nails.

UIAppearance Is Better Than You Think

You already know about the UIAppearance protocols added to iOS. You know that UIAppearance makes it WAY simpler to customize the appearance of the common UI elements is iOS. You probably know that you can customize the appearance of the duly marked UI_APPEARANCE_SELECTOR methods on your own subclasses as a means of differentiating certain elements from others of the same type (such as specifying a class of UIBarButtonItem as a cancel button and therefore always red).

What you might not know is that it’s trivial to use UI_APPEARANCE_SELECTOR on your own custom subclasses for visual elements that are not in the standard set of appearance selectors.  Here’s a quick example of how you might use this:

Say you have a particular class of view you have all over your application that has border around it (using the CALayer backing the view).  You could hard code this look into a view subclass, or you could do it the hard way by setting this on every individual view.  You can also use a UI_APPEARANCE_SELECTOR on your custom class and set it with an appearance proxy.  This functionality and behavior falls squarely under “I can’t believe it’s this easy”.

Here’s the interface:

#import <UIKit/UIKit.h>

@interface TestView : UIView

@property (nonatomic, retain) UIColor *backgroundColor UI_APPEARANCE_SELECTOR;
@property (nonatomic, retain) UIColor *borderColor UI_APPEARANCE_SELECTOR;
@property (nonatomic, retain) UIFont *font UI_APPEARANCE_SELECTOR;
@end

Here’s the implementation:

#import "TestView.h"
#import <QuartzCore/QuartzCore.h>

@implementation TestView
@dynamic backgroundColor;
@dynamic borderColor;
@synthesize font = _font;

- (void)drawRect:(CGRect)rect
{
    NSLog(@"%@", self.font);
}

- (void)setBackgroundColor:(UIColor *)backgroundColor
{
    [super setBackgroundColor:backgroundColor];
}

- (UIColor *)backgroundColor
{
    return [super backgroundColor];
}

- (void)setBorderColor:(UIColor *)borderColor
{
    self.layer.borderWidth = 4.0;
    self.layer.borderColor = [borderColor CGColor];
}

- (UIColor *)borderColor
{
    return [UIColor colorWithCGColor:self.layer.borderColor];
}

@end

And in the App Delegate:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    self.window.backgroundColor = [UIColor whiteColor];

    MainViewController *mainView = [[MainViewController alloc] initWithNibName:@"MainViewController" bundle:nil];

    self.window.rootViewController = mainView;
    [self.window makeKeyAndVisible];

    [[TestView appearance] setBackgroundColor:[UIColor blueColor]];
    [[TestView appearance] setBorderColor:[UIColor redColor]];
    [[TestView appearance] setFont:[UIFont systemFontOfSize:12]];
    return YES;
}

And here’s the result:

And the NSLog prints the font that was set:

2012-05-16 17:03:43.517 test[26634:f803] font-family: “Helvetica”; font-weight: normal; font-style: normal; font-size: 12px

What’s the advantage?

Well it depends on your development strategy and the scope of the project.  For large, running projects it’s helpful to separate as much of the presentation code (fonts and colors) from the logic of the application.  This allows you to keep all of your styles centralized in one place as opposed to littered throughout a bunch disparate classes in much the same way that CSS can separate presentation logic from the HTML structure of a website.  Additionally, if you’re writing framework level code for a static library it offers greater flexibility and code reuse where you’re not as able to edit the implementation of a class.  This of course all depends on the purpose of your app.  For once-and-done style apps it may not make quite as much sense.

Technical notes:

You will find that if you tinker around that the UI_APPEARANCE_SELECTOR macro isn’t really necessary.  In fact, the code above will work just fine without it.  The macro #define’s to nothing, so I’m not personally sure if there’s more grandiose future plans for if it’s just a placebo macro to let developers know what will be guaranteed to be supported.  In truth, virtually any display related property on a UIView can already be set using UIAppearance proxies, though like all non-official APIs Apple can change that without notice.  By taking the approach above you’re likely future proofing your code for later.  If I were to take a guess at the internals of UIAppearance it seems like a clever hack on KVC more than a real, run-time enforced protocol.

Regardless, there’s a lot of power to be exploited using this protocol and it should change the way you think about creating a great visual style for your apps.

A Quick Gotcha About Blocks

Blocks are a great addition to the iOS SDK and C standard, especially for predominantly event driven applications as we commonly see on the iPhone and iPad.  There’s a quick gotcha that a junior developer here at Mindgrub reminded me of the other day.

While blocks are a powerful tool, if you’re not careful they can start to degrade the quality of your app by introducing retain cycles.  Retain cycles occur when two objects in your application keep strong references to one another.  Take the common table view for example.  Ordinarily, the view controller containing (owning) the table view acts as the datasource and delegate for table, providing the necessary information for displaying the number of rows and supplying cell objects.  If you look closely at the properties on UITableView for datasource and delegate, you’ll see that both properties are declared as “assign” or “weak” in ARC.  This is critical particularly in the case where the view controller is also the datasource/delegate.  If the properties were “strong” or “retain” you could easily wind up in a retain cycle where neither your UITableView nor your view controller would ever be destroyed, thereby leaking memory.

This can happen with blocks as well and it’s not always so obvious.  Let’s say we have a view for which we define a block to handle the user tapping it.  The code might look something like this:


#import <UIKit/UIKit.h>

typedef void(^TapBlock)(void);

@interface TapBlockView : UIView
{
   TapBlock tapBlock;
}

@property (nonatomic, copy) TapBlock tapBlock;
@end

@implementation TapBlockView
@synthesize tapBlock;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
   tapBlock();
}

- (void)dealloc
{
   [tapBlock release];
   [super dealloc];
}

@end

This is a very convenient way of setting up delegate style behavior without having to litter your code with lots of protocol definitions. Now an example of using the view in a view controller:

- (void)viewDidLoad
{
    [super viewDidLoad];
    tapBlockView = [[TapBlockView alloc] initWithFrame:CGRectZero];
    [tapBlockView setTapBlock:^(void) {
        self.someLabel.text = @"You tapped it!";
    }];
}

Everything seems fine right? Nice and convenient.

Not so fast.

Blocks automatically scope capture and retain any object types you use in the block. In this case that variable is “self”. Now we have a retain cycle since self owns the tap view which owns the block which now owns self.

According to Mike Ash, the correct way to handle this is to use a weak pointer (assign) in the block like this:

- (void)viewDidLoad
{
    [super viewDidLoad];
    tapBlockView = [[TapBlockView alloc] initWithFrame:CGRectZero];
    __block typeof (self) weakself = self;
    [tapBlockView setTapBlock:^(void) {
        weakself.someLabel.text = @"You tapped it!";
    }];
}

By using a weak, nonretained pointer along with the __block modifier we’ve broken the retain cycle. For ARC code you should use __weak instead of __block.

There’s two important lessons to be pulled from this. The first is that you always have to be aware of the code you’re writing and look for subtle retain cycles like this one. No amount of automatic reference counting magic can help you in some of these scenarios. The second is that it’s always good to look at code written by others on your team because there’s nearly always something new to learn to refresh on, even if you’re one of the more seasoned developers and the code you’re reading is from a junior dev.

For more information check out these two articles on Mike Ash’s Friday Q&A Site:
9/30/2011 – Automatic Reference Counting
4/30/2010 – Dealing With Retain Cycles

Where the hell have I been?

I always the “sorry I haven’t posted a blog in a while” posts, but this is one.  This blog is largely dedicated to iOS development bits that come across, and in short I haven’t been doing a whole lot of iOS lately.

I’ve been spending my time working with Drupal to craft web services for Mindgrub’s ongoing project.  It feels odd to be back in the PHP world again and especially strange to be working on Drupal.  In light of what I’ve been working with lately, I’ve got a couple of things I’m planning to work on for this site soon:

  1. Wrangling Drupal to expose services for use with iOS, or literally anything else.  Drupal is nice, but I find the lack of documentation for what I perceive as very simple things frustrating but it’s very common and very popular.  There may certainly come the day when you might be asked to connect to Drupal as part of an iOS development project.  I plan to outline creating a content types module in code as well as services to feed your iOS app.
  2. A practical guide to RestKit.  RestKit is in active development, so a lot is changing every day.  That makes most of the tutorials on the web a little out of date.  I plan to write a guide to using RestKit where you have an existing iOS app with an existing CoreData model in place.

One of my goals for the year was to branch out a bit.  I’m not sure that PHP and Drupal are exactly where I wanted to go, but onward nonetheless.

Speaking on iOS5 tonight at Frederick Web Tech

I’m speaking again tonight at the Frederick Web Tech meetup about some of the “new” features available in iOS5.

You can check out the meetup page here.

There’s also a GitHub and Slideshare link.

A Lesson In Knowing Your Product

Long ago, in my first year at Mindgrub we were contracted to work on a community site that circled around creating a sense of nostalgia.  You could go in and become fans (or something) of things from your 80s childhood.  The site details really aren’t important, and I’m not even sure if the site is even still around anymore.  Regardless, we were working with other far flung contractors to bring this whole nugget together, and it wasn’t happening.  At all.

I remember sitting in weekly conference calls discussing the merit of the PHP site architecture, templating systems, database backends.  Tons of nitty gritty details that really had absolutely nothing to do with creating a community site.  Phrases like “so when when we’re done the templating system will work just like smarty” were uttered often (clarification: not by us, we were only making some javascript widgets).  Usually someone would follow with “then why the fuck aren’t we using smarty?”.   I recall this verbatim.

The situation continued to spiral into more and more delays as we trudged along. There eventually was a call between our CEO and theirs where our CEO asked why they’re so focused on software development when what they were trying to build was a community site, not a software system.  I imagine the silence was deafening.

It was a bad case of “not invented here” syndrome.  Symptoms include burning tons of time and energy on something that quite simply has A) already been done, B) probably better and better tested than you could do it, and C) completely ancillary to your core business.

That conversation came ringing back all to true to me on a recent project.  We were looking to add a rich PDF viewer to an app with paging, zooming, and all the other bells and whistles.  For a few days I looked on the internet, found some sample code, and toyed with some of the Apple examples for displaying PDFs.  I got something that worked, sort of.  One stray rotation of the device could throw the whole thing out of whack.  I was trying to avoid having to pay for a library that does all these.  Then it hit me.  The goal of the app was not to display PDFs, it was merely one facet of it.  I has already been done, better than I could have done it in the time we had to do it.  Displaying PDFs was not the business goal of this application.  I was doing nobody any good by continuing to churn on it.

The lesson here is to know what your product is, whether it belongs to you or you’re ultimately helping someone else create theirs.  It’s always important to recognize that using a well tested pay-for component might just the thing you need to add the value you were looking for and get everyone back to focusing on what’s really important.

Do Just About Anything With Blocks

I love using blocks in objective-C (and C for that matter).  I think they’re the most useful additions to language since . . . well I don’t know.  I allows your code to be more compact and more logically grouped (remember UIView animation delegates? yeesh).  In some cases, even faster by backgrounding certain operations with GCD.   Sadly, blocks have only made it into a small portion on the SDKs and frameworks, most notably collection enumeration and the vastly improved UIView animations.  Fortunately there’s some enterprising individuals and groups who’ve created some very good libraries for extending blocks to other parts of the framework.

BlocksKit

BlocksKit is an open source library that allows you to do just about anything with blocks.  You can easily apply blocks as selectors to UIControls, UIGestureRecognizers, and NSTimers.  There are facilities to apply blocks in different ways to collections, and through the use of dynamic delegates you can use blocks in place of delegates on alerts and action sheets.  As a bonus there’s some handy utilities for dealing with associated objects too.

Block based drawing

I’ve shared this before,but David Hamrick posted a great demo on using blocks to handle drawing on UIViews without the need to subclass.  Find it here.

UIAlertView+Blocks:

If you don’t need everything in BlocksKit, you can check out UIAlertView+Blocks which works very nicely for working with alerts and actions sheets without the need for a delegate at all.

Note: BlocksKit and the above categories don’t play nice together.  You’ll need to pick on or the other to avoid some very odd runtime bugs.

Some block tips of my own:

Static comparators

Apple added block based comparisons for sorting NSArrays.  The block takes 2 objects and returns an NSComparisonResult.  If you find yourself sorting the same thing in multiple places it’s often faster to statically declare your comparator that you can reuse.  Let’s say we have an array of a custom class person, with strings for first and last name:


@interface Person : NSObject
@property (nonatomic, copy) NSString *firstName, *lastName;
@end

Sorting using a block is simple enough, given an array of Person objects:


[people sortUsingComparator:^NSComparisonResult(id p1, id p2) {
if ([[p1 lastName] isEqualToString:[p2 lastName]])
{
return [[p1 firstName] caseInsensitiveCompare:[p2 firstName]];
}
return [[p1 lastName] caseInsensitiveCompare:[p2 lastName]];
}];

If we want to reuse the comparator multiple places, we store it into a static variable:


static NSComparator personCompare = ^NSComparisonResult(id p1, id p2) {
if ([[p1 lastName] isEqualToString:[p2 lastName]])
{
return [[p1 firstName] caseInsensitiveCompare:[p2 firstName]];
}
return [[p1 lastName] caseInsensitiveCompare:[p2 lastName]];
};

// ...

[people sortUsingComparator:personCompare];

You can do the same thing with literally any block you want to reuse, but you don’t get the benefit capturing scoped variables.

Blocks in forms:

It’s common to have forms made of table cells with text fields for entering user data.  Normally to properly apply the captured data you either have to do some creative work with UIView tags or extend the UITableViewDelegate to hand your new cell type.  You can also use blocks to handle the callback by either adding a block variable to a custom table cell.


typedef void(^TextViewEndCallback)(NSString *enteredText);

@interface MultiLineTextFieldCell : UITableViewCell <UITextViewDelegate>
{
UITextView *textView;
SBTextViewEndCallback textViewEndCallback;
}
@property (nonatomic, retain) IBOutlet UITextView *textView;
- (void)setTextViewEndCallback:(TextViewEndCallback)callback;
@end

The above example uses a text view in a table cell.  The table cell should be delegate for the text view.  In the text view delegate method you need only call the block passed into the cell:


- (void)textViewDidEndEditing:(UITextView *)textView_
{
textViewEndCallback(textView.text);
}

This is very easy to use in your cellForRowAtIndexPath method:


__block SomeClass *object = [objects objectAtIndex:indexPath.row];

[cell setTextViewEndCallback:^(NSString *enteredText) {
object.somestring = enteredText;
}];

We used very similar ideas to the above in SalesBag to speed development along.

That’s it!

I enjoy how blocks can speed development along and allows you to write more flexible and sometimes even more reusable code.  Have any cool block tricks?  I’d love to hear them.  Happy Coding!

Printing a C array in the debugger Console

I’m by no means a GDB expert.  I know the basics, but I just learned this gem today.  Say you have a C array with five items created with something like this:


int *array = malloc(5 * sizeof(int));

And you want to print it out in the debugger quickly.  You can’t just print the pointer because GDB doesn’t know to print it as an array, but this will:


p *array@5

Output:


$1 = {0, 0, 0, 0, 0, 1}

To use this the left hand side, before the ‘@’ should be an array, and the right hand side needs to be the length of the array.  Very handy.

Follow

Get every new post delivered to your Inbox.