Sunday, January 11, 2015

Resources for Beginning iOS Development

Recently, a coworker was interested in learning iOS development and asked me to recommend to him a few resources for learning and I thought that I would also share this here.

Here are a couple resources for learning iOS:

Intro Books
1. iOS Programming: The Big Nerd Ranch Guide (4th Edition) - This book only covers iOS 7 and Objective-C, but a lot of the same concepts will apply in iOS 8. This would be good intro to iOS and also learning Objective-C. Some of the text might be out of date since the Xcode UI has changed a little bit. I originally started learning with the Beginning iPhone Development book (below), and I read this one after; I thought that the Big Nerd Ranch book went in to more in depth on almost all the topics and I was able to pick a few tips on how to better structure my code.

2. Beginning iPhone Development with Swift: Exploring the iOS SDK - This book is also gives a good intro to iPhone development, but this one is written for iOS 8 and is in Swift if you want to skip the Objective-C part.

Learning Swift
1. I recommend just reading Apple's book on Swift to learn the language. It's available in iBooks here and on the web here
2. There is also a second part of the book above that covers using Swift with Cocoa and Objective-C, which goes into more advanced topics but is a good follow up read after reading the first part. The iBooks link is here.

A common question I see is should I learn Swift or Objective-C? I think that if you are looking for a job as a iOS developer, you will need to learn both because most likely the company/client already has existing code that is in Objective-C. You can mix and match Swift and Objective-C code, but you need an understanding of both to do so. If you are able to develop an app from scratch, you can probably get away with only learning Swift. It is also good to point out that the 3rd party library support for Swift is very weak right now, so if you don't mind reinventing the wheel (a good way to learn) then this is the way to go. You can also always refer to open source libraries written in Objective-C and convert them to Swift yourself (another benefit for learning both languages).

Other resources (tutorial sites and blogs)
1. http://www.raywenderlich.com/ - This site has a lot of useful tutorials for not only beginners but also intermediate and advanced iOS developers. When I was first starting out, I frequented this site and tried to do as many tutorials as I could. Even still today, I find myself visiting this site to continue learning.
2. http://nshipster.com/ - This iOS blog is written by the creator of AFNetworking and has a lot of in depth articles on Cocoa, Objective-C and Swift topics that are commonly overlooked.
3. https://iosdevweekly.com/ - This newsletter is a great way to get a pulse on the iOS community. I've been able to learn about a lot of useful tools and libraries from this weekly email.
4. WWDC videos (all years) - The videos from the WWDC presentations are extremely useful, but can be quite advanced and dry sometimes. If you are unsure of what the best practice of doing something is, I would recommended these videos; It's also a great way to learn about the new things that were introduced in every new version of iOS. Also see ASCIIwwdc.

Hopefully this is a good enough start. There is also always the Apple docs (sometimes confusing and hard to find), Google and Stack Overflow. Good luck!

Tuesday, December 30, 2014

Productivity Tools

There are several tools that I use daily to help improve my productivity not only as a developer, but also as a regular computer user. I think it is important to share these types of tools, interesting tidbits, or libraries on a weekly basis because there are just so many new things being created all the time.

For example, I went to a few Ruby on Rails meetups and the first item on the agenda was always "Sharing of Tools and Tips"; here people would share new Ruby gems they had discovered or even share their experiences in solving a recent problem. Another great example is the Ruby Rogues Podcast where after every show, each speaker has picks that they share with the group; these picks aren't always technical, but it's a great way to be cognizant of what is out there. At my current job, we have tech talks every Thursday, but before we start, I reserve 10-15 minutes for sharing of tools and tips or just anything that people found interesting for the week. Usually atleast one thing of interest comes from it, and I think just that makes the entire exercise worth it.

Here are my picks:

1. BetterSnapTool



Ever need to compare two windows side by side, but find it a pain to resize and arrange them all the time? BetterSnapTool makes this simple, and can snap windows to any side you want with just a keyboard shortcut. You can also define custom hotspots where if you drag a window to it, it will resize that window to a custom size that you previously specified. This is a paid tool, but I know that there are probably similar tools that are free.

2. Alfred

Alfred allows you to do a lot of things from your fingertips. With a keyboard shortcut, it launches a spotlight like prompt that lets you search for files, launch applications, and even do arithmetic. I have to admit, I have been using this a lot less lately because the new spotlight in Mac OS X Yosemite is quite good. But I use to use this to launch all my development apps after logging in. You can also launch gmail straight from the prompt. I haven't explored this yet, but there is a PowerPack that you can purchase that allows you to define custom workflows. For example, I could define a development workflow, and it would allow me to launch all of my developer applications with one keyboard shortcut.



I've built a lot of bad habits when using computers since I was young; I use to sit at the computer for 8-12+ hours straight and not take breaks. This has caused me a lot of eye and hand problems as I grew older, and I learned that it is REALLY important to take regular breaks from the computer. This tool helps remind me to take 10 second breaks, every 20 minutes, and 10 minute breaks every 60 minutes. This is all customizable as well. An important exercise I learned from my optometrist is the 20/20 rule, which is every 20 minutes, take a 20 second break and look at something atleast 20 feet away.


A little more heavy weight than the default Notes app, but I like it because I can type up notes for a presentation on my laptop, and then access these same notes on my phone during the presentation. You can also categorize your notes in to notebooks, which has been useful because I create a lot of notes.

4. zsh and the oh-my-zsh plugin



I've mostly just used bash shell since it is the default on Mac OS X, but I recently decided to try zsh because I've heard a lot about it. There are a few nice features in zsh that bash doesn't have, but I wouldn't say anything ground breaking. To list a few:
  • Inline glob expansion: For example, type rm *.pdf and then hit tab.
  • Interactive path expansion: Type cd /u/l/b and hit tab.
  • Customizable prompt configuration options.
What I enjoy the most is what the oh-my-zsh plugin offers. The plugin basically offers a nice way to manage your zsh configuration, but it comes a ton of built in plugins and themes. I mainly just use a theme and a git plugin (which can probably be done in bash too with aliases), but it is still definitely worth checking out. I am sure that I am only scratching the surface. Here is my zsh config if you would like to take a look.

5. Animated Tabs for Chrome


Lastly, I wanted to show an anti-productivity tool that I use quite often in Chrome. Usually I'll want to search for something, so I'll open a new Chrome tab and then I'll see some funny animated gif and then forget what I was doing and even what I was searching for. Although this interrupts my productivity during the day, sometimes it is nice to take a little break and laugh :).

Here are a few other tools that have been recommended to me by colleagues, but I just haven't had a chance to check them out yet:
  • Fluid App
  • Caffeine - Prevent computer from going in to screensaver or turning the display off on battery. This is useful for Skype calls or meetings where you're watching someone else's screen but not interacting with your computer.
  • Dash - For local copies of documentation for various platforms and libraries. Its nice having a local and searchable copy.
  • LastPass - For account management
  • Pauses - An alternative to Timeout
  • Flycut - Clipboard manager
  • Filedart - Speedy file sharing

Saturday, November 15, 2014

Git Merge Workflow on Github

How to Merge Code

Below is a guide that I wrote for a recent project explaining a git merge workflow on Github. Often times, when you develop a new feature, you will create a new branch off of master called a feature branch. On the feature branch, you might have many commits to save your progress, or when you complete certain milestones of that feature. Once you finish the feature, you will want to merge this branch back to the master branch. However, you might not want all your commits to show up in the git log history because they were only for development purposes. We can overcome this issue by using a feature of git called interactive rebasing which allows you to squash certain commits and customize the commits that will eventually show up once the branch is merged to master. I have described the steps to achieve this outcome below.

Table of Contents


Purpose

This guide explains how to develop and commit your code using git and GitHub. A developer should create a feature branch when developing new code. In the feature branch, a developer may commit multiple times during development including making changes based on comments from a code review. When development is completed and the feature branch is ready to be merged in to the master branch, the developer should squash the commits in to one, so that the git log history is kept clean.

Detailed Steps

1. On the `master` branch, `git pull` to make sure your code is up to date.

2. Create a feature branch `git checkout -b name-of-feature-branch`. Note, you will automatically be switched to this new feature branch you are creating.

3. Write code and develop your feature.

4. `git commit` your code. Note, this step may be performed as many times as you prefer during development in order to maintain a history of your code changes.

5. Once development is completed (and all your code is committed), we should make sure that our code is up to date with the latest `master` branch. On your feature branch, `git rebase master` will ensure that your branch is up to date and your code is compatible with the latest `master`. Also this step ensures that your commits are at the top, which is critical for the next steps. Note that, during the rebase, you may encounter merge conflicts that will need to be resolved.

6. Now we need to push our code to GitHub. `git push origin name-of-feature-branch` (while on the name-of-feature-branch branch) to push the branch to GitHub.

7. In GitHub, create a pull request for the name-of-feature-branch branch and assign someone to review your code.

8. If the reviewer makes comments or suggestions, please address them by asking for clarification and/or committing the changes. The reviewer also needs to give approval on whether or not the code is ready to be merged.

9. Once the code is ready to be merged, it is time to squash your commits. Note, this doesn't apply if you only have one commit to merge, and in that case you can just merge your pull request on GitHub. First we need to know at what point your branch and master diverge. This is required as you only want to squash your commits.

10. To do this run `git merge-base master `. This command should spit out a commit hash such as _918310dca623fac2d46198324814695c4726017e_. You will then use this hash to tell git "_squash the commits from this point on_".

11. Once you have your merge base commit run `git rebase -i `, for example: `git rebase -i 918310dca623fac2d46198324814695c4726017e`.

12. Your text editor should popup and you should see your commits with the word `pick` in front of them. For all commits except the first one, change `pick` to `squash` or `s`, which will squash all of these commits in to one. Now save and quit your text editor.

13. Another text editor window should pop up now, and here you can enter the commit message you would like to show up. This commit contains all of your commits squashed together.

14. In order for this to work with your existing GitHub pull request (because we are rewriting the git log history), we need to `git push origin name-of-feature-branch -f`, which forces the push to overwrite the git log history in that pull request.

15. You should see that on your GitHub pull request, the history should only contain the one commit that you squashed.

16. Press the Merge button, and don't forget to delete your remote feature branch!

Additional Reading

Tuesday, August 19, 2014

Coding Styles and Standards

One of the main reasons for having coding standards is to keep your code readable by everyone. By enforcing standards and formatting, the code base becomes consistent, and anyone can easily understand the structure of the code because he will be more familiar with what to expect. It is also very useful when a new developer joins the team because once he is familiar with the patterns, he will be able to easily read the existing code, which results in a more pleasant experience.
In this example, I will define coding standards for an iOS project (which uses Objective-C). We will take advantage of the fact that code formatting can be automated in XCode by using a plugin. The coding style that I chose is based on the Chromium style guide, but I made a few modifications, which can be found in the `.clang-format` file. Feel free to make changes as you see fit; All of the options are defined here LLVM Coding Standards.
Installation
1. Install Alcatraz, the package manager for XCode.
`curl -fsSL https://raw.github.com/supermarin/Alcatraz/master/Scripts/install.sh | sh`
2. Select `Package Manager` from the `Window` menu and search for `ClangFormat` and install that plugin.
3. Select `Clang Format` from the `Edit` menu, and click on `File`. This will load formatting settings from the `.clang-format` file that is located in the repository.
4. When you want to format a file, go to the `Clang Format` menu and select `Format File in Focus`. You can also enable `Enable Format on Save` to have the plugin automatically format the file when you save it. You can also bind formatting to a keyboard shortcut, refer to the ClangFormat homepage for more options.

Additional Standards

The automatic code formatter does not implement all the standards we would like to follow. There are some standards that need to be enforced by the developer himself because they can't be automated. Please refer to https://github.com/paulsfds/objective-c-style-guide to see some examples.

Other Languages

Coding standards are universal and there exists some popular ones for other languages. I would also suggest searching on Google for popular standards for your favorite language. Also, many well established companies such as Google have their own coding standards that are available to the public. Here are a few popular ones to take a look at:
JavaScript
Ruby
Objective-C
C++
What are your favorite coding styles and standards?

Monday, February 3, 2014

Upgrading Your iPhone App to iOS 7: The New Status Bar

Hi everyone,

It's been a while since I last blogged. I've been neglecting my blog posting duties, but I hope to start posting more here this year. I've picked up iOS development in the meanwhile, so I'll be posting some posts on that topic in addition to the usual Ruby on Rails ones.

I'll start with this post that I wrote for work: http://blog.grio.com/2013/10/upgrading-your-iphone-app-to-ios-7-the-new-status-bar.html

Thursday, April 19, 2012

Ruby Metaprogramming with class_eval

One of the really cool and exciting aspects of using a dynamic programming language like Ruby is that you can generate code dynamically at runtime. Yup, you heard me, at runtime. Try doing something like this in Java. This is one of the features that allows all the magic that happens behind the scenes in Ruby on Rails possible. For example, this is how Rails' attr_accessor automatically creates getters and setters for you. If you don't remember, you can call attr_accessor in an ActiveRecord class to define a "virtual" attribute, or in other words an attribute that isn't persisted in the database table. I want to explain this idea in more detail by creating a new method called attr_accessor_with_history, which is similar to attr_accessor, but it will also store the attribute's history. Say we have the following class:
class Test
   attr_accessor_with_history :sample
end
Then this is how the attr_accessor_with_history method should work in the Ruby console:
t = Test.new
t.sample = "test"  # => "test"
t.sample = 1       # => 1
t.sample = :abc    # => :abc
t.sample_history   # => [nil, "test", 1, :abc]
So how can we do this? Let's first create a new file called class.rb and put the following inside:
class Class
   def attr_accessor_with_history(attr_name)

   end
end
By defining our method in the class Class, all Ruby classes will be able to use it. This is because in Ruby, all classes are an object of the class Class. You can find more information in the API here. The second thing we want to know is that Ruby provides a method called class_eval, which takes a string and evaluates it in the context of the current class. So in our example, the class Test is calling our method, so when class_eval is called, it will be evaluated as if it were called in the class Test.

Let's take care of the easy part first, which is creating the attribute's getter methods. This is pretty straight forward because we don't really need to do anything special here.
class Class
   def attr_accessor_with_history(attr_name)
      attr_name = attr_name.to_s         # make sure it's a string
      attr_reader attr_name              # create the attribute's getter
      attr_reader attr_name + "_history" # create bar_history getter

      # write our setter code below
      class_eval %Q(
                  def #{attr_name}=(attr_name)
                  end
                 )
   end
end
The %Q is Ruby syntax for an interpolated string, which allows us to create a string, and it will also interpret Ruby values such as anything in #{}. So in thinking about how to define our setter, we need to store the previous history of the variable. How can we do this? Well we can store stuff in an Array. If we push things in to the Array like a Stack, we can also figure out the order in which things were inserted. The one thing we need to be careful about is the initial case where we should initialize the array, and also insert the first value as nil. This is what we get:
class Class
   def attr_accessor_with_history(attr_name)
      attr_name = attr_name.to_s         # make sure it's a string
      attr_reader attr_name              # create the attribute's getter
      attr_reader attr_name + "_history" # create bar_history getter

      # write our setter code below
      class_eval %Q(
                  def #{attr_name}=(attr_name)
                     @#{attr_name} = attr_name

                     unless @#{attr_name + "_history"}
                        @#{attr_name + "_history"} = []
                        @#{attr_name + "_history"} << nil
                     end

                     @#{attr_name + "_history"} << attr_name

                   end
                 )
   end
end
First we set the value of the variable. Second, we check if the _history array has been initialized yet, and if it hasn't, then go ahead and initialize it. Lastly, we insert the new value into the _history array.

That was just a quick example of some of the cool things you can do with metaprogramming in Ruby. I want to end by showing a real world example of how I used metaprogramming on a project I'm currently working on. If you haven't read my previous blog posts, I'm working on a Rails site using MongoDB (with the Mongoid gem) that deals with computer games. I have a class called Event, and I need to define some scopes based on the game type so that I can do queries such as Event.all.starcraft2, which would return all Events that have a game attribute of 'starcraft2'. I could easily hard code these scopes, but it will be annoying to always have to add a new scope every time we add support for a new game. Instead I can dynamically create these scopes using Ruby metaprogramming.
  class_eval %Q(
              #{Constants::GAMES}.each_pair do |key, value|
                scope key, where(game: value)
              end
             )
First I need to explain the Constants::GAMES variable. I created a dynamic_fields.yml file that stores all the games that my application supports. Please refer to my previous post here for more detailed information. So when my application loads, it reads in that YML file into the Constants::GAMES variable, which is a hash. The key is the game name as a symbol, and the value is the game name as a string. For each game, it will create a scope with the same name (as the game), and it does all of this automatically. I could have wrote a line of code for each game, but this is much cleaner to write and easier to maintain in the future.

Friday, April 6, 2012

Installing and compiling Ruby from the source code

There are several different ways to install Ruby with the most popular being RVMand rbenv. Both have their advantages and disadvantages, but rbenv is a newer and more "lightweight" Ruby installer. I'll let you Google the differences between RVM and rbenv if you are more curious. I decided to install Ruby by downloading the source code and then compiling it myself. I'll be installing Ruby 1.9.3-p125 (the latest version as of writing this) on Debian Linux 6 (Squeeze).

1. First we need to install some development tools and libraries that Ruby needs to compile. Run the following commands from your terminal:
   apt-get install build-essential vim git-core curl

   apt-get install bison openssl libreadline6 libreadline6-dev zlib1g zlib1g-dev libssl-dev libyaml-dev libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev

   apt-get install libcurl4-openssl-dev libopenssl-ruby apache2-prefork-dev libapr1-dev libaprutil1-dev

   apt-get install libx11-dev libffi-dev tcl-dev tk-dev
Note you may need to run these commands as root or use sudo.

2. Download the latest version of Ruby here: http://www.ruby-lang.org/en/downloads/ under the Compiling Ruby — Source code section.

3. Extract the tar.gz file e.g. ruby-1.9.3-p125.tar.gz by typing:
tar -xvf ruby-1.9.3-p125.tar.gz
4. Open the README and follow the instructions on how to compile and install Ruby.
./configure
make
make test
make install
The install process will probably take a while, but once it's done, we can test to see if ruby installed successfully by typing "ruby -v" in the terminal. You should see something like, "ruby 1.9.3p125 (2012-02-16 revision 34643) [i686-linux]" if ruby installed correctly. Next we can install the Bundler and Rails gems to make sure Ruby is working correctly.
gem install bundler
gem install rails
Lastly, create a new Rails project to test to make sure everything works!