Types vs. Objects

by mattjdrake on July 28, 2009

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:

int number;

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:

NSNumber *numberObject;

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.

number = 78;

The NSNumber object requires more work.

numberObject = [[NSNumber alloc] initWithInt:78];

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

[numberObject release];

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.


ShareThis.jpg
if(LIKE){
  //Please:
  [self.comments writeThisComment:@"Replace with your words"];
  [youTube subscribeTo:self.videos];
  [digg diggThis:self];
  [yourBlog linkTo:self embedVideoOrNil:self.video];
  [twitter reTweetThis: self];
}
http://howtomakeiphoneapps.com
Please share this if you like it!
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • email
  • FriendFeed
  • LinkedIn
  • MySpace
  • Ping.fm
  • StumbleUpon
  • Suggest to Techmeme via Twitter
  • Technorati
  • Tumblr
  • Yahoo! Bookmarks

Comments on this entry are closed.

Previous post:

Next post: