Types vs. Objects

Matthew Campbell, July 28th

binary-heart.jpgYou will encounter two kinds of variables when working with Objective-C. Objects such as the UIAlert and simple types like integers and doubles. These things can cause some confusion because they follow different rules even though they are used in similar ways.

The first notable difference is how we declare a type versus an object. Here is how an integer would be declared:

The type and a variable name followed by a semi-colon. Pretty simple and probably what you would expect. Here is how a NSNumber object would be declared:

This is the class name and a variable name prefixed by an asterisk. It is similar to the integer we created above but it must include the asterisk. The asterisk simply means that this variable is a pointer to a space in memory.

The next significant difference is that while the integer above is ready to use, our object have memory allocated to it and our object must be created with an constructor.

eBookAd1.001.jpg

The integer is easy.

The NSNumber object requires more work.

Finally, when you are finished working with an object you need to make sure to release it.

When you are finished working with the integer you can just forget about it.

Objects also need special care when it comes to memory management. They are worth the extra trouble since objects generally contain a very rich feature set and are used extensively in the Cocoa-Touch frameworks.