BuySellAds.com

Read the chapters in my new book Barcodes with iOS 7 as I hand them in. Great new app opportunities await!
Our DNA is written in Objective-C
Jump

Category Archive for ‘Recipes’ rss

Setting Pre-Compiler Defines

Once you get smart enough to build multiple apps from the same project you probably have to wrap your head around the concept of #define and #ifdef to conditionally activate and deactivate portions of your code. What is somewhat unnerving is that the target build settings change their appearance seemingly uncontrollably and I took a while to work out what triggers this morphing.

The difference lies in what settings you choose in the upper left hand corner of XCode. Only if you select the “Base SDK” setting then the dialog is the most user-friendly.

Base SDK

The build settings for the active target can no be reached by right-click on target, Get Info, build tab. Or alternatively menu option “Project”, “Edit Active Target”. I discovered three places where #define statements can be placed. I am going to show them to you and make a recommendation as well.

Read more

Understanding Autoreleasing

Do you really understand when you need to retain and release some object? And what about autorelease? It took me around 3 months before I grasped when to use autorelease and now it’s second nature to me. But when I needed to explain to a coding buddy I was stumped. I found that my approach was one of feeling rather than knowledge.

So I decided it was time to do an experiment to visualize what happens to the retain count and when an instance is really released. So see what’s happening to our crash test dummy class I made a TestClass that overrides all the important methods so that we get an output to NSLog what is happening.

First I want to demonstrate how the retain counter – present in all Objective-C classes – is used to automatically determine when the instance can be freed from memory. Then I am going to show how to use a factory method which returns an autoreleased instance to make your life easier.

Read more

URL Encoding

When transmitting data in the context of the HTTP protocol you often need to encode text in a way that does not interfere with special characters used in URLs. This is of importance if you want to put unicode characters into an URL query but also for simple things like constructing a body for a HTTP POST request. A form post also takes the form fields and puts them into the form that you know from an URL: field=text&another=more. That’s what the HTML content type “application/x-www-form-urlencoded” means.

The first thing that jumps out of the documentation when looking for a standard function to achieve such “URL Encoding” is stringByAddingPercentEscapesUsingEncoding. So that is what I was using for encoding the password for my iTunes Connect class which drives MyAppSales. And until now this worked without a hitch until customer #113 who was the first to use a plus character in his password. The poor guy ended up locking his iTunes account. Sorry!

It turns out that + is an anachronistic special character substitution for a space. I would have expected for it to be encoded properly by the above mentioned method as %20, but this is not the case.

Read more

Your Own Delegation Protocol

Usage of delegates is prevalent throughout the SDK’s that Apple provides. A delegate is basically a way to tell a standard object “Hey you, if you need some info or want to inform somebody when something happens, talk to this guy. I’m outta here”.

This achieves three things that are an essential skills in programming:

  • you make use of a component without having to do extra work of subclassing it for customization
  • you appoint somebody else to do the work of one-the-fly customizing (the delegate)
  • you can excuse yourself and go to the pool

A good example of usage of delegates is UITableView. This standard class, to be found in UIKit, knows and speaks two protocols: UITableViewDataSource and UITableViewDelegate. As the names suggest the first deals with questions related to the content of the table to be displayed: number of sections, number of rows, headers, individual row cells et cetera. The second delegate, which is also called delegate, deals with interactions on a higher level, like if you tapped on an individual cell. Even though they are called different, both are delegation protocols and if you like you can assign discrete classes to data source and delegate for a table view.

To make this a practical example I will show how to make a class that informs your code when a headset is plugged in or plugged out.

Read more

Determining the Hardware Model

Not all Apple Hardware is created equal. For some apps you need to distinguish between different models of iPhones and iPod Touch. But when you query the model property of UIDevice you don’t get enough information to really know what hardware your app is running on.

With a little bit of googling I found an article on Ars Technica explaining how the pros are getting the kind of information that we regular dev guys dream of having at our fingertips. It basically uses barely documented system calls to get the infamous model string from which you can infer the real device model.

We are talking about sysctlbyname which Apple even documents as a standard C library function call to “get or set system information”.┬áiPhone Dev crack Erica Sadun made this UIDevice category extension. We are inspecting it with awe as we see the magic unfold.

Read more

__MyCompanyName__ Treats Warnings as Errors

I finally figured out three XCode settings that I’ve been dreading to change for quite a while now. See if you didn’t think of changing them yourself as well, but could not be bothered to Google them.

Are you still working for __MyCompanyName__?

If not you might want to change what XCode puts into the standard header which is being generated for all new files.

//
//  Report.m
//  ASiST
//
//  Created by Oliver Drobnik on 24.12.08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

There is no UI method of changing this string which is kept in the XCode preferences file. Instead you have to use a command like this.

defaults write com.apple.Xcode PBXCustomTemplateMacroDefinitions '{"ORGANIZATIONNAME" = "Drobnik.com";}'

The result being that from now on all code belongs to your company, even if it’s just a company of one.

Read more

Detecting Internet Connectivity

For the latest version of GeoCorder Apple required me to show an alert if there was not internet connection. This is meant to prevent “user confusion” which would occur if the user is expecting something to happen staring at his screen, but nothing happens because of lack of data connectivity.

There is a good example from which you can steal the technique, but it took me some experimenting to find the right mix. For some reason that escapes me the regular connectivity check would only work within the sample, but not in my own code.

Read more

Advanced Sorting of NSArray with Functions

I’ve already discussed previously how to sort NSArray with descriptors and selectors. Even how to unsort it i.e. shuffle it. You can use descriptors to sort by KVC-compliant properties. Selectors you would use if the objects contained in the array have a comparison method themselves.

For those special cases where you neither have properties nor a suitable sort method built into the objects to be sorted you have to resort to the third and last method of sorting an NSArray: with a specialized sort function.

For two projects I need to sort an array of NSDictionaries. Here I’ll show you how I did it.

Read more

Target-specific Headers

Often you will add multiple targets to your project file to build variants of the same app. For example if you have a Lite version or Ad-sponsored variant using the same source code you would definitely save yourself a lot of work having a single project and then multiple targets.

While I was helping a colleague merging three projects into one we found it impossible to assign headers to single targets. You can assign source code, images and lots of other file types, but why oh why no headers? How would we make sure that from 3 Constants.h files always the correct one would be used?

There are of course methods out there which propose to either have a script replace the headers or use an ugly contruct like this:

#if defined(TARGET_1)
#import
#elif defined(TARGET_2)
#import
#else
#error Must define a TARGET macro!
#end

I you you too are cringing from seeing such code. Surely there must be a more elegant solution. I searched, and I found not one but TWO.
Read more

Custom Back Button on Navigation View

When you push a view controller onto a navigation stack, the back button will always show the title of the previous view controller. This can lead to ugly effects if the title is too long. But then again, you want long titles on your view controllers because you don’t want to let the title bar space go to waste.

The method of how you can customize the back button is a little bit counterintuitive, but it was shown on episode 13 of the Standford lectures. [Here my I came to a screetching halt]

When I went to search my Blog for the link to the Standford stuff, I also found that I had already posted exactly the same recipe already one month ago. And ┬áIt’s still valid, even though I did not remember posting it. This serves to show that you might not be as productive at 5 am in the morning as you would assume. Memory is lacking then.

Well, just to put in at least something new, here is a before and after visual illustration:

Before:

Before

After:

After

Go to the previous article “Shorter Back Buttons