More on my last
This addition to the Reactive Cocoa readme came across my twitter feed this morning. It seems like Reactive Cocoa might bring to life a lot of the ideas I mentioned in my previous post. The MVVM pattern is certainly interesting.
Lessons from AngularJS

AngularJS
The past two weeks I’ve been working on a web project using AngularJS. Angular is a Javascript MVC framework with the backing of Google. I always enjoy taking some time to learn a new language or tool from time to time. As iOS developers I think there’s a couple of concepts we could learn from Angular.
Bindings – Bindings everywhere.
One of the first thing you learn in Angular development is its two way binding system. Placing a binding in your HTML template is dead simple; simply enclose the variable in the handlebars: {{myvar}} or link it via the ng-model attribute on an input tag. The binding is two way such that changing the value of a text field will update that in your model.
Unfortunately iOS is often much more difficult and manual when it comes to keeping your model and UI in sync. MacOS provides bindings to developers but there’s no once and done solution for iOS. However binding is not difficult to implement using KVO. KVO has its downside when it comes to performance, but it may be worth it for the simplicity. I haven’t tried to implement it myself to be able to tell.
Thin models; thin controllers
Angular makes very few assumptions about what your model in the MVC way of thinking is. In fact, the model for any controller is expected to be a special variable called the $scope. The $scope object is provided by the controller, whose entire job is to do nothing but populate the scope. Compared to iOS view controllers, Angular controllers are extremely light.
iOS view controllers have a bad habit of being very involved in both in view-ish things and model-ish things, as well as its dictated function of handing controller-ish things. How many times have you managed a view directly in your view controller as well as managed changes back to the model? Probably a lot. One of the downsides of UIViewController is that they often wind up being behemoth and barely manageable monster objects. Angular’s documentation strongly advises that you don’t make changes to the DOM (the literal view of a web application) from within the controller, delegating those tasks elsewhere. The result is a very simple controller that does its job of exposing the model to the view well and without needless other operations.
Greater separation of the view and the controller
Web applications have an inherently strong presentation layer: the HTML and CSS that handles display in the browser. In Angular style, the HTML provides structure of a view, CSS provides the presentation of the view, and Angular does the job of providing data to the view. As mentioned above it’s all too common in an iOS application to jam all this functionality into a single view controller.
It’s not a stretch to say that UIViewControllers are often required to do far too much for any non-trivial application. A view controller might be responsible for loading data from somewhere, maybe through an NSURLConnection, doing any formatting or transformation of the data, creating a view in loadView: and laying all the pieces out. It may also be the datasource and delegate for a table view providing cells and handling cell selection. After all of that it might also be accepting event callbacks from UI controls and altering the model appropriately. That’s a huge set of tasks and I’m as guilty as anyone of writing multi-thousand line view controllers.
Applying the lessons
So how should we break up a UIViewController subclass into more manageable chunks? I think Angular presents a couple of ideas.
- The most simple task is to separate the model related concerns of a UIViewController from its view related concerns. In iOS development you need to have view controllers, but there’s no rule that you can have other controllers to handle other tasks. NSFetchedResultsController provides a great example of a way to separate the needs of dealing with CoreData from the other responsibilities of the view controller.
- Relegate the UIViewController subclass to what its name implies: management of the view. Offload data related concerns to a custom defined model controller.
- Make views a little smarter. HTML and CSS provide a natural separation between controllers and views. Interface builder is one of the best tools and iOS developer has but there’s no reason we can’t make smarter views that know more about it’s layout and the properties of it’s subviews. If reuse is concern there’s nothing wrong with the root view of a view controller being a custom subclass that arranges other pre-made components.
- Attempt bindings using KVO. You could easily inject a transformer into the mix for formatting.
Fully realizing these are all a little abstract right now I’m planning to take a concrete stab at these in some future posts. For now the takeaway is that learning a different way of doing things can always open your eyes to some better ideas in your current workflow.
Mastering Copy and Paste in iOS – Part 1
System wide copy and paste is built into most of the stock iOS controls without the developer having to do any extra work to enable the feature. Sometimes for security purposes you may wish to lock down the functionality (to not allow copy and paste at all) or disallow copying and pasting between your app and other apps that may be on the device. Restricting this functionality is a pretty common requirement for the growing market of security frameworks out there for enterprise applications such as GOOD and MobileIron. They commonly refer to this as “data leakage”.
In this 3-part series I’ll explore the copy and paste system in iOS and how you can use it to fit the needs of your specific application.
This first part will focus on locking down the copy and paste system completely.
In the second part I’ll show you how you can create an application specific pasteboard to allow copy and paste within your own application while still preventing data leakage to other apps as well as posting other types of data to UIPasteboard.
In the third part I’ll explore other types of data on the pasteboard with simple drawing sample app.
Locking down copy and paste
All controls in UIKit expose a single method you can override to control actions such as copy and paste.. To lock down system wide we really only need to implement a category on the specific controls. In preparing the sample code for this I attempted a category on UIResponder, but that seems to have unintended side effects. Adding it to the classes directly seemed to be the most consistent approach.
At a high level you’ll want to use code like this:
@interface UITextField (lockdown) @end
@implementation UITextField (lockdown)
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
SEL copy = @selector(copy:);
SEL cut = @selector(cut:);
SEL paste = @selector(paste:);
if (action == copy ||
action == cut ||
action == paste)
{
return NO;
}
return YES;
}
@end
You can find the sample code for this here that will lock down UITextField, UITextView, and UISearchBar. Remember that since this method exists on UIResponder, you can use it to lock down any control, even complex ones like UIWebView.
One more note:
When you first implement this you may notice that you get a compiler warning about reimplementing a method in a category that already has an implementation elsewhere.
You can prevent this code by wrapping it in the following:
#pragma clang diagnostic push #pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation" // ... #pragma clang diagnostic pop
Be sure to check out part 2 of this series for digging deeper into copy and paste and the UIResponderStandardEditActions protocol.
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:
- 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.
- 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.


