Author Archives: Lou Franco

Managing memory in iPhone applications

I program all day in C# and C++ at my day job, so Objective-C is both natural to me (because of a mostly familiar syntax) and unnatural (because of it’s many differences). In terms of memory management, Objective-C splits the difference between C# and C++. On the iPhone, Objective-C does not have a GC, but NSObject (the base class for all of your classes) supports reference counting. Of course, you could build the exact same mechanism in C++, but it’s pervasive and included in ObjC and there’s also some support in the app runtime for an autorelease concept (release will get called for you on an object at some point when the runtime has control — you are safe in the rest of your stack frame).

When I first started Habits, I didn’t really read through the entire memory management API (there were so many other APIs to read) because I have been using reference counting for a long time (old COM programmer) and the awesome leak detector included in XCode was a good enough guide to what I was doing wrong.

However, the rules are really simple, and now that I know them, I never run into memory management issues:

  1. Declare all of your object pointer @properties as retain unless you have a really good reason not to. Then the setter that is generated will automatically call retain when you assign. When you reassign, it knows to call release on the old value.
  2. In your dealloc, assign all of your @properties to nil. This has the effect of calling release on the current values if they are not already nil.
  3. alloc returns an object with a reference count of 1 — so you have to balance with a release.
  4. If you alloc, then you should try to release in that same function. To retain the value, assign it to something that retains. Exceptions are if you are a factory function that is returning a value up to be retained by the caller.
  5. Obviously, each retain call needs a release.
  6. Built-in convenience functions return objects that are autoreleased. That means you shouldn’t call release on them — the framework will call release at some point (they are registered in an autorelease pool that that is serviced when you return back to the framework). If you created the object without an alloc/init pair, you don’t need to call release unless the docs say you do (but they probably don’t)
  7. Check all of your work with the leak detector. Also, if you crash, you’re probably doing it wrong — I will have more to say on that soon.


I highly recommend that you read
Very Simple Rules for Memory Management in Cocoa on stepwise.com. Keep in mind that the suggestions for building proper setters is handled automatically if you declare your @properties correctly.

iPhone Development Tips

Having now gone through getting Habits built, tested and on the App Store, I wanted to share these tips on getting started with iPhone development:

  1. Go enroll in the iPhone developer program before you start. Yeah, I know — it’s 99 bucks. But if you have an idea and a reasonable chance of doing it, just take the plunge. I joined after I finished, and that caused a lot of delays — I could have been completing the other necessary steps in parallel.
  2. As soon as you’re in, go get your application contracts going. If you want to make paid applications, you have to give Apple your tax and bank information. Again, it takes some time to get approved, so start early.
  3. If you don’t know Objective-C — don’t worry, that’s the easy part. The primer on the iPhone developer site should be good enough if you know C/C++.
  4. For Cocoa Touch, I recommend Erica Sadun’s iPhone Developer’s Cookbook. The chapter on coverflow is worth the price of the book, but everything else is there too (navigation, touch, location, contacts, etc)
  5. I also highly recommend iCodeBlog. Once you have some basic knowledge of the framework, check out the to-do application tutorial.


Update: just found this great flowchart of the right order to do things

Announcing Habits

I have been working on my first iPhone app for the last few weeks. It is a GTD companion application to help with recurring to do items with an indefinite schedule. It’s called Habits, because I think it will help you form (good) habits. Soon to be available on the App Store.

Business of Software Pecha Kucha

Had a lot of fun with my Business of Software Pecha Kucha. My topic was Engineering the Evaluation Funnel, or how companies that have downloaded evaluations can still track usage with being creepy and sending back information from the application.

I’m going to be recording a version of my presentation and posting it soon.

Are Tech Books Broken?

I was just flipping through a new book on a specific mainstream technology from a major publisher. The topic is interesting to me and the book looks like it’s probably fine, but I’ll never know, because it’s over 600 pages and I don’t have the time to devote to this topic. I don’t want to pick on this book, because it’s not just this one, but pretty much all mainstream tech books.

It reminded me of this Martin Fowler post on Duplex Book style. In describing a new 883 page book:

But xUnit Test Patterns isn’t as scary as it looks, because it’s actually two books in one set of covers. […] The first book is a narrative book, designed to be read “cover to cover”. The narrative book is something small enough to be digestible, in xUnit Test Patterns it’s 181 pages […]. The second book is reference material, which is designed not to be read cover to cover (although some people do) but instead to be dipped into when needed. The idea is that you read the narrative book to get a good understanding of the field, then put it on your shelf so it’s handy to grab when you need to delve into the reference section. 

This is the style that the GoF Design Patterns book is written in as well, and I think it works great. Fowler goes on to talk about what it would mean to fully embrace the style (e.g. should it be physically two books, should the reference part be online only).

Fowler and the GoF probably both use this style because it’s used by Christopher Alexander (the architect whose patterns books the software pattern movement borrows from heavily). In A Pattern Language [ad], Alexander describes how the form of the patterns is designed for skimming through them — each pattern has a bolded introductory paragraph, a bolded solution paragraph, and a labeled diagram of the solution. You only need to read the rest of the chapter if you are interested in the details.

But even without embracing duplex styles, I think tech books could be much shorter. Here’s a list of some of the books on my shelf that look a half-inch wide (about the 200 page range):

  • The C Programming Language, by Kernighan and Ritchie
  • UML Distilled, by Martin Fowler
  • JavaScript: The Good Parts, by Douglas Crockford
  • Presentation Zen, by Garr Reynolds
  • The Non-Designer’s Design Book, by Robin Williams

I consider these books to be essential, and find myself picking them up over and over. Even the next step up in thickness (Designing Interfaces, by Jenifer Tidwell and Programming Collective Intelligence, by Toby Segaran) are very quick and enjoyable reads.

I’d like to see publishers try a 200 page book for topics that they usually address with a 600+ page one, and perhaps consider duplex styles if they feel they need to deliver a larger book. The issue is that they’d be going against the grain, but if they genuinely did a great job in a shorter format, I think the word of mouth would help — like it did for O’Reilly’s Head First series.

20 Days of Clojure: Day 20

Last night was our Clojure event with Rich Hickey. BTW, if you were there, regular meeting of the Western Mass Developers Group are every other Thursday at Panera Bread in Hadley (7pm) — most of the time, we just sit around and talk — very informal — hope to see you there.

Back to the presentation — hopefully the slides/video/etc will be up somewhere soon — Rich focussed on the concurrency features of Clojure (Vars, Refs, and Agents). First he showed us the state of concurrency support in Java/C# today (locking) and identified the problem as having direct references to mutable objects. Clojure offers only immutable atoms and datastructures so that’s how he addresses one part of the problem. However, since the mutability is how the world works, Clojure models change as a change to what a reference points to. So, if you view the world through refs, it will appear to change. Then he introduced the controlled ways in which refs can change.

1. Vars are essentially thread local variables. They are a reference whose changes can only be seen in a single thread — each thread gets an independent and isolated view of the variable. Like thread-local variables — they are a very simple way to take code that looks like it’s manipulating global state and give each thread its own isolated copy.

2. Refs are mutable references to immutable objects. They can only be changed inside a transaction and all changes to all refs in a transaction appear to have happened at the time the transaction ends (to other threads). Inside the transaction, the changes are immediate. When two transactions are open and change the same ref, the second one to finish is automatically retried (so you should have no side-effects inside of transactions). All Refs read inside of a transaction will return the value that they had at the start of the transaction (so are consistent with each other).

3. Agents (which I have explained before) are for asynchronous changes to a reference. Each agent hold a value and you send actions to it to change the value. Only one action will happen to an agent at a time and you can read the current state of the agent any time. Rich spent a little time to caution us against any comparison to Erlang’s actors. They are a different concept with different tradeoffs. Agents have the advantage that they can be read from any thread conveniently (just dereference) whereas actors require sending a message to read (which is asynchronous). Clearly, Erlang’s benefit is location transparency (for distributed code) — which is what it was designed for. Rich hinted that Clojure might have an Actor concept, but it would not be unified with Agents.

What was new to me with agents is that there are two types of message sending mechanisms — send and send-off (which appear to be undocumented right now) — Rich used send-off which dedicates a thread to the agent (rather than run the action from a thread-pool). This is how you have to do it if agents block at all (which ants do because they have a small sleep).

Then, he showed us an ant simulation — I think he will make the code available. In short, there is a square world of cells, each one holds a Ref to what is in the cell (food, ant, pheromones, home base). Ants are represented by agents, which are sent a behave message. Behave picks a random action for the ant to do (move, turn, pick up food, drop food) and then mutates the world of cells in a transaction, then it sends itself another behave action. There is an agent responsible for painting the world, and another which evaporates pheromones in the background.

Anyway, the demo was impressive — since painting makes a copy of the world in a transaction, it has a completely consistent view of the world. Refs make sure that all changes to them are in transactions, so you have language support for where you need cooperation (contrasted to locking, which is not enforced). Agents also help you model the real world in a way that a coordinated single-looped simulation (calling behave on ants in a loop, then paint over and over again) could not.

And clojure’s agent mutating mechanism (sending a function to it), means that agents don’t have to have any knowledge of the messages that might be sent to it (again contrasted to Erlang Actors). Finally, various messages can take different times to complete and that would be represented in the simulation — some ants might complete several small actions in the time it took another to complete one (which would not be the case in a behave loop).

I’ll have more on this when the slides, code, etc are available.