Pimp My Cat App

Let’s add more features to our cat feeding app from last week to give it more flavour.

Background Image

First let’s add a background image. We want our image to be compatible with Retina-display iPhones, so it should have a resolution of 640 x 960.

  1. Find a suitable image to use.
  2. Resize it in an editing tool like Photoshop and create two versions:
    • Background.jpg at 320 x 480 pixels
    • Background@2x.jpg at 640 x 960 pixels
  3. Drag the images to the Project Navigator (on the left) in Xcode.
  4. Leave the options at their default values and click Finish.
  5. Open the Storyboard and drag a UIImageView to the bottom of the ViewController stack.
  6. In the Attributes Inspector (on the right), set the Image field to Background.jpg.
  7. Set the Alpha to a value near 0.25.

Tidy Code

Let’s add our new initializer to Animal and use it when creating our Cat and Mouse objects.

Header Source

User Defaults

The Foundation framework includes the very useful NSUserDefaults class, which can be used for storing settings and options for your app. It’s basically a type of persistent NSMutableDictionary, meaning that its contents are saved even when you quit the app.

The NSUserDefaults instance used is retrieved using the + (NSUserDefaults *)standardUserDefaults class method.

Values are set using setXXX:forKey: and retrieved using xxxForKey:. Note that you can pass primitive types (like int, float, and BOOL) as values, and that keys must be of type NSString.

The - (BOOL)synchronize method is called to save the changes to disk.

Let’s add user defaults to our app to remember the cat’s weight between different runs of the program.

First, we’ll add a new updateWeight: method to handle any changes to the Cat weight.

We can now store and retrieve the weight from the user defaults.

Text Input

Let’s add a new UI control for setting the Cat name.

First, let’s add the name property to the Cat class.

Header Source

Next, let’s add a UITextField to the view.

  1. Open the Storyboard and drag a UITextField to the top of the ViewController stack.
  2. Connect an outlet to the ViewController.
  3. Connect an action from the “Did End On Exit” event to the ViewController.
  4. In the Attributes Inspector (on the right), set the Placeholder field to Name Your Cat!.

Then, let’s add some code to read the name from the input field.

Header Source

Finally, let’s store and retrieve the name in the user defaults.

Comments are closed.