Fork me on GitHub

In any kind of environment, visual marks ease and enhance the comprehension of information. Countless researches studied the best way to display data, which colors induce what emotions, the association of geometric shapes with pre-formed concepts. The fact is that a sign or plaque draws much more attention than plain text. After all, an image is worth a thousand words, therefore, an image sends a much more significant message than some written words.

That’s one of the reasons many development tools have featured badges (or  shields) to inform the status of an application/framework/library/etcetera. It’s the case of Travis CICode ClimateGemnasium, among others, all following olivierlacan/shields` trend, available Github.

I’m an iOS developer and previously have worked with Python/Django (though I still fool around) and I’ve always found very interesting this creative way of sharing the state of a service dynamically, but sadly, there were no solution to Python nor iOS featuring badges (except for Travis CI for tests). But, recently, appeared - out of nowhere - pypip’s shields for Python packages that allows the visualisation of the latest available version of a package on pypi or how many downloads some release *had.* When I came aware if it I resented for taking so long for solution so simple and effective to come up (or at least for I to discover it)… but it got over the top when I found out… or better, did not found out a similar solution for Cocoapods.

I’m one of those who doesn’t miss a chance to solve a problem and endeavour an opportunity. That’s how the Cocoapod Badges  project started. Since Cocoapods doesn’t provide an API, any info on the number of users/downloads, nor any kind of useful data, it proved to be a challenge, and all I could use had to be what was at hand: the latest version of a pod. But even though, mistaken are those who thought it easy. As mentioned, there’s no API!

Cocoapod Badges NSStringMask 1.1.2

Digging through Cocoapod’s and Cocoadocs’ websites, I tried, first, to use the documents.jsonp  file that I found in the source of the pod’s documentation website, however, I soon gave up for realising that its update frequency is too high (above one hour). At last, I had to content with the unfortunate /search?q= requested when searching for a pod in Cocoapod’s main page. At first, it looked like an excellent solution since it returned a json object with some info, until I realised that inside the object was a string with some html code and only inside that code was the pod’s latest version. “God dammit!” Now I have to run a request on a “pseudo-webservice” and parse it with XPATH to get the latest version!

Super easy! But, as my mother would on a brazilian saying: “few shit is silliness”. The damned “API” doesn’t return the requested pod, but anything with the searched string. To get something more useful, I figured that  /search?q=name:POD_NAME searches only in the pod’s name and not in its description, what significantly reduces the results, specially when dealing with popular pods such as AFNetworking.

After all that suffering, I finally got the information I wanted, but then, how do I show it in an image? Olivier Lacan’s repo, that enabled all the existing  badges, provides, beyond the .png to existing services, .SVG vectorial files that render xml data to images. So, accidentally, I double-clicked the  .SVG file and the holy Google Chrome opened it as an image! Finally good news! As the information about the version is in plain text inside the xml, all I had to do was to set the mimetype so Django could provide the file as an image.

Heroku dyno later and the service is available fulltime (depending on Cocoapods website) through the images’ url:

http://cocoapod-badges.herokuapp.com/v/$PODNAME/badge.png

All you have to do is replace the $PODNAME with the name of the pod you want. Simple and easy, isn’t it? Use it at will! And suport the Github repo!

This is an article I originally wrote for the brazilian online magazine DevMedia’s Mobile Magazine. This first part is the article’s introduction, so seat back and relax. Soon I’ll post the second - and final - part with a tutorial to the Apple like documentation generator appledoc.

“In the agile programming environment, using methodologies such as SCRUM, Agile and Lean, we can’t always document our sources. After all, pragmatics as we developers are, why would we lose time if the documentation won’t be compiled, won’t do any difference in the code’s performance and demands a considerable slice of our time? But despite all that, the lack of documentation hurts. A lot.

Who’s familiarised, knows that in the ultra accelerated rhythm of startups, where everything is at the top of the list, there’s not always time to apply some of the good programming technics that aren’t crucial to the sanity and speed of the code. Oftenly, there’s no time to formally test classes and methods because of the virtually null due time that is given. It’s easy to find developers awake all night in hackatons to successfully deliver that key feature that will make “the whole difference”. Test? Document? Review? There’s so much to do and so little time!

That’s the reality of many young developers who enter this ultra competitive environment searching for the dream of running their own companies. The responsibilty of satisfying potential investors, the pressure for deploys and the client’s needs frequently obfuscate technics that improve development and maintenance experiences, but that are not considered primordial to the construction of an application. How often didn’t I went back to an undocumented code done less than two months before and thought “what the flock does this loop do?” or “why, on earth, is this class here and not there?” Of course, when those lines of code were written, everything made perfect sense, but the moment those ifs and fors went out of the conscious mind, their meaning were long gone. After all, quoting the chinese saying: “the ink is better than memory”.

So let us document. It doesn’t hurt, doesn’t make you fat and isn’t illegal. Actually, documenting is like eating vegetables: no one really likes it, but we do it hopping that, in the end, it’s worth the result. But unlike the vegetables, it’s proved that documenting helps. Contrary to the common thought, the time spent documenting a day’s work is reasonably irrelevant and the benefit in return is definitely worthy. With practice and experience, no more than 30 minutes can be lost documenting everything that was made in a whole day. That way, the developer stays focused in his activity and doesn’t deviates doing other stuff that draws his attention or stand in his way of writing the best possible algorithm. Therefore, don’t wait until the end of the week, when the work pile up, part of the features were already forgotten and we’re all dying to that ice-cold friday-night-beer. Personally, I recommend documenting in the end of the day. In my case, it’s always the last thing I do before leaving, because everything is still fresh in memory and the amount of code produced in one day doesn’t compare to what’s done in one week. If that’s not enough, I realised that I do a final unconscious revision before the final commit when I’m passing by the code documenting it.

A well documented code is good for everybody. What would be of us without the independent frameworks, packages and repositories used daily if they weren’t documented, or even had a bad documentation? Even senior programmers, frequently, return to Apple’s documentation to a better understanding of Cocoa’s classes. Whether consulting a less used protocol, or lower level functions to manage sockets, threads or semaphores. Nobody can remember everything, so don’t try it, you’re not an elephant. It’s not rare to find developers who use the documentation as a last resource to understanding some tool. This line of thought makes sense if we think that we want everything to be as explained as possible so we don’t lose any time trying to interpretate any possible use, when trying to comprehend some feature. But we must never forget that even when visiting forums, asking more experienced developers or reading articles in blogs, EVERYTHING had a documentation as basis. Well, even this article wouldn’t exist if wasn’t for appledoc’s documentation.

Documenting - or at least commenting - source codes is fundamental to the intelligibility of the code. Implementing these technics with developers that never done it, oftenly is seen with prejudice and suspicion that are common to the staunch and stubborn nature of young programmers. I must confess that I didn’t wanted to document when people first told me to. Moreover, because of it’s so unusual syntax, it’s interesting to verbalize what’s developed in ObjC to ease it’s lecture, specially by more unexperienced programmers.

As time goes by, with the expansion of the startup, the pressure and need of code documentation is felt. Contrary to many programming languages - such as Java with it’s hideous GUI Javadoc - Objective-C doesn’t have an “official” documentation generator. In our quest to find a differentiated framework, which could make us feel as if we were really making difference, we found the excellent appledoc that, using code comments à la Javadoc, generates Apple like documentation, with a docset automagically installed in XCode, static HTML sources which can be uploaded to a cloud (vide  NSStringMask which uses appledoc) and an interface identical to Cocoa’s.

Among appledoc)’s already described advantages, are also the documentation parsing through code comments, wich allow the developer to consult the documentation without the need of opening a new window, since everything is in the code. The integration with XCode allows the visualisation of tooltips with quick access to the documentation by simply holding the Option key and clicking a method or class. Moreover, by “compiling” appledoc) in your documented project, the library’s docset is already imported to your Organizer. Simple or not? But, undoubtedly, appledoc)’s main advantage is it’s interface that’s identical to Apple’s documentation. I think it’s very unlikely that there’s any ObjC developer that has never read Cocoa’s documentation, be the one embedded on XCode or the on in Apples developers portal. By reusing the known model, it terminates the problem of having to familiarise to a new layout.”

Soon I’ll be posting the second part with a tutorial.

Fork me on GitHub

When developing, we often come across code we’ve seen hundreds of times that we just copy and paste from project to project. Sometimes it’s so banal that it’s not worth trying to improve, change or even modularize it. Ctrl-C + Ctrl-V may be the cheapest and fastest solution, ergo, the best.

This is the kind of situation we see when masks must be applied to text fields such as Social Security Numbers (SSN), Telephones, Zip Codes, and so on. Those awful few dozens of lines we copy from one textField:shouldChangeCharactersInRange:replacementString: to the other. It never changes because it works. There’s no need to improve it. It’s always the same. But I’ve got tired of it. That nasty code that, in a well structured class, can be as a mole in a beautiful woman’s face.

A few days ago I got some spare time and I started working on something I though could come handy. So how do you simplify and generalise this problem that every developer has to face at least once? Easy! Regex! Wait.. You sure it’s easy? I’ll tell you, it wasn’t easy, but we’re talking about patterns in varying occasions and, as I visualised it, regex is the best, simplest and most “approachable” solution. I mean, everybody knows a little bit of regex.

While modelling, I wanted to make it as simple and as clean as possible, therefore, for now, there are only two classes, and only one method you’ll really use, but you can read the complete documentation. From now on, I’ll present a superficial approach to introduce this small library.

Fork the Github Repo!

NSStringMask

The NSStringMask is the main class responsible for applying your masks to the NSStrings. Among it’s methods the only noteworthy is [NSStringMask maskString:withPattern:placeholder:].

It formats the given string based on the pattern you provide, filling the voids with the placeholder. It automatically creates an instance of NSRegularExpression with the option CaseInsensitive, so if you need a different option, you may use the alternate method which expects a regex instead of pattern.

There’s also an alternative method that receives no placeholder (same as nil), in this case, when the given string is shorter than expected, instead of applying the mask, the method will return a cleaned string having only the valid characters based on validCharactersForString:.

Important Note

Doesn’t matter if providing a pattern or an instance of regex, the regular expression must have capturing groups (parentheses). This is because the class understands that everything that is not within parentheses is part of the mask and must be interpreted as literal characters!

Suppose you’re formatting a SSN, whose regex pattern is \d{3}-\d{2}-\d{3}. If you provide that regex/pattern, nothing will be formatted because the class will think that \d{3} is part of the mask, and not 3 numbers that should go there.

The correct usage is: (\d{3})-(\d{2})-(\d{3})

// RIGHT:
NSString *result = [NSStringMask maskString:@"12345678" withPattern:@"(\d{3})-(\d{2})-(\d{3})"];
// result = @"123-45-678"

// WRONG:
NSString *result = [NSStringMask maskString:@"12345678" withPattern:@"\d{3}-\d{2}-\d{3}"];
// result = nil

Obs: If Xcode is showing a warning about unknown escape sequences, try adding double slashes (\\d)

UITextFieldMask

This is a subclass of UITextField, so you can set your nibs to use this class and automatically apply masks to your text fields.

Obviously, you must provide a mask to transform your strings, and it’s recommended that you do so when initialising your view or view controller. So you should set the text field’s mask inside viewDidLoad or awakeFromNib.

Suppose you have a view with an outlet to an UITextFieldMask named textFieldMask:

- (void)awakeFromNib
{
    NSStringMask *mask = [NSStringMask maskWithPattern:@"(\d+)"];

    textFieldMask.mask = mask;
    textFieldMask.delegate = self;
}

A question for you: what does that mask accepts?

Installation

You can install it from Cocoa Pods, or clone the project from the Github Repo and copy the files in the folder Classes.

Helpful stuff

I’ve also created this gist with some common patterns. Feel free to improve it!

Tired of having to find out where an exception occurred, that was only captured in the main()? Now I’m going to show you the best Xcode tip that no one talks about. Don’t ask me why.

These are the very few steps that will save your life and make your day better.

Creating an “Exception Breakpoint”

The first thing to do is to access the Breakpoint Navigator, which is the little breakpoint marker on the top of your Project Navigator. If you didn’t know, the Breakpoint Navigator show all your breakpoints in your project, where you can easily manage them. (Click on the image to see it bigger)

best-xcode-hint-1

Now that you’re in the Breakpoint Navigator, click on the little “+” button on the bottom left of the screen. A little dialog window will show up and choose the “Add Exception Breakpoint…” option.

best-xcode-hint-3

Then, the Xcode will ask you some information about the breakpoint you’re creating:

best-xcode-hint-4

  • Exception: There are three options: “All” to get all types of exceptions; “C++” to get only C++ exceptions; and “Objective-C” to get only ObjC exceptions. I like to leave it as “All”.
  • Break: Leave it as “On Throw”. This way, the execution will stop when your code throws an exception and not when it catches, which is the default on main().
  • Action: You can set some action to be performed when the breakpoint is reached like run an Apple Script, shell command and others. I’ve never used it.
  • Options: if you check this option, your code won’t stop when the breakpoint hits, making it useless. So leave it unchecked.

Congratulations! You’ve successfully created an Exception Breakpoint that will stop whenever something odd happens! Let’s try it out!

As an example I’ve created an empty array and tried to access the object at index 0, which doesn’t exists. This is what happened:

best-xcode-hint-5

Whoa! The Xcode stopped precisely where the problem was! Quite awesome, huh? But, sometimes, it’s not that easy to visualise what the problem really is, so if that’s happening to you, just hit “play”, and the code will keep executing as if your breakpoint doesn’t exists. What happens now, is the main() catching whatever exceptions that may happen.

So you can look at the console to see what the problem was:

best-xcode-hint-6

”-[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array”

Ta daa! I know it’s not perfect. It won’t get any signals (SIGABRT, SIGTRAP), flags or bad access kinds of witchcraft, but I think it’s super helpful and I think you guys should know.

SQLite sucks. I think everybody knows, but I had to say it. But, sometimes, we have no choice other than using it. Even though it’s horrible and we know we`ll be frustrated, once in a lifetime, SQLite may be the best choice. Wether developing a program with a tiny or fast persistence. Sure there are other alternatives that may suit you best, but the platform we’re using may not support it.

For instance, I’m currently working on an iPad app that will have a fairly big amount of data which must be available offline and it will have to be updated sometimes. The best solution we came with is a background server task wich will build an SQLite database populated with the most recent data and, when the user requests, the iPad will download the whole database, overwriting any existing ones.

I’m no DBA, but I don’t think anyone writes database creation scripts anymore. At least not for the usual CREATE TABLE, etc. I’m mostly a MySQL guy and, for a long time, I’ve been using MySQL Workbench to create my DB models and syncing with my existing database. It automatically creates everything that needs to be created and alter all tables that must be altered without losing any data (most of the time). It’s pretty good and I never had any problems with it.

Now, back to listing reasons why SQLite sucks (dude, you can’t add a constraint when altering a table!). As any platform/framework with no “official” team, SQLite depends on the community to increase it’s awesomeness. Therefore, as everybody knows SQLite is not awesome, no one really waste time developing a good administration tool for it. What may happen, is a company own a DB management program (such as Navicat) and something like this goes by:

- Hey, we're supporting MySQL, SQL Server, MongoDB, Cassandra, NoSQL and Postgree,
don't you think people will notice we're ignoring SQLite?

- God dammit *gasps*, add support to it too... but don't lose too much time with it!

Unfortunately, there are no really good tools to work with SQLite available. “Hey, what about Navicat?” It’s okay, but I found tons of bugs in the Mac version. If that’s not enough, are you really willing to pay to use a management tool for a free, open source database? But if you search deep enough - like the 3rd page of Google - there are also some weird stuff that appears such as SQLiteStudio (for Mac). When I see things I like that I think “why the hell would people lose time developing something for SQLite?” But hey, there are weirdos for everything, so I’d like to thank for the SQLiteStudio team for being strange enough to create it.

Even though it’s not the best tool ever, SQLiteStudio sure comes in handy and helps a lot, but it doesn’t solve the mentioned problem of modelling your SQLite database and not dealing with SQL scripts. So, searching for something that would fill this void I found this excellent script in Lua for MySQL Workbench that automagically generates the SQLite CREATE script from a model. It’s super easy to install and use. Just follow this steps:

  • Download the .lua script (duh!)
  • Click in the “Scripting” menu in MySQL Workbench.
  • Click “Install Plugin/Module”.
  • Choose the downloaded .lua script.
  • ???
  • Profit.

That’s it. Now, if you want to try, open a model, click the “Plugins” menu and under “Utilities” there must be an option named “Export SQLite CREATE Script” which may be the first one. Just click it and choose where to save the .sql script and execute it. Voilà! If you have any problems executing the generated script, you may need to comment the BEGIN; at the top and the COMMIT; at the bottom of the .sql script.

Super easy, isn’t it? Give it a try. Even if, like me, you hate SQLite. The plugin solves the modelling problem, but creates a new one, because you can’t ALTER an existing table since it only generates the CREATE script. But if that’s not a problem go for it and be happy. When I found it, life suddenly became joyful again.