github

Using Regular Expressions Part 2 - The Cocoa Connection

Last time, in Part 1 of this series, I wrote about the basics of regular expressions, and the phrases I tend to use. Today, I’m going to talk about the mechanics of how I use Regular Expressions in Cocoa.

##But first, an historical diversion

In my opinion there are, two different ways that programming languages implement Regular Expressions: The perl/ruby way, and the Java/C#/Python/Cocoa way.

In ruby and perl, regexes are implemented directly on the String type, whereas in the other languages, there a separate object that contains the functionality. Here’s what you need to know to do a regex substitution on a string in ruby:

myString.sub(‘pattern’,‘replacement’)

clean, easy, and immediately useable if you know what pattern you want to use.

Here’s what you need to know to do the same thing in Cocoa:

+[NSRegularExpression regularExpressionWithPattern:(NSString *) pattern 
options:(NSRegularExpressionOptions)options error:(NSError **) error]

-[NSRegularExpression replaceMatchesInString:(NSMutableString *) string 
options:(NSMatchingOptions)options range:(NSRange)range 
withTemplate:(NSString *)template]

which is not clean, not easy and contains a bunch of stuff you have to go look up to be able to get started. What are NSRegularExpressionOptions and

NSMatchingOptions? What’s a template? Do I really have to create an

NSRange for this? And that leads to the obvious question: Is all this effort really worth it?

Now I don’t know about you, but I don’t want to spend any effort remembering any of those option parameters, and I don’t want to take the time to look them up any time I want to use a regular expression. To me, the beauty of Objective-C is that it gives us the ability to build most of what you need to know directly into the method signatures.

 7 min read

Steal This Code and Protect Their Data: Simplifying KeyChain Access

##The Code The last couple of months, I’ve been working on my first Mac App (more on that in a later post). As part of this App, I’m calling a REST API that requires that I have the user’s password for that service to use in the API calls. Although that API is a minor part of the App, and although the service doesn’t have horrible consequences if someone gets the user’s password for it (in my opinion at least), there was no way I was going to store that password on disk unencrypted.

 4 min read