Adventures in the transition from C to Cocoa.

Friday, June 15, 2007

Cocoa Objects

Objects in Cocoa are very similar to objects in other languages such as C++ or Java. Their structure and syntax is very different though. While C++ and Java objects are essentially extensions (in syntax and organization) of the struct in C, Cocoa's objects are implemented in a completely different way, with a completely different syntax.

In C++, you'd create a class using some code kind of like this:

class myClass
{
private:
int anInteger;
float aFloat;
public:
void someMethod(float f);
int someOtherMethod(int i, float f);
};


and you'd have a class called myClass with 2 private member variables and 2 public member functions, or methods.

If you wanted, you could define the member functions inside the class declaration itself, or you could define them outside the class like this:

void myClass::someMethod(float f)
{
aFloat = f;
}


This would define the someMethod method of myClass. Because you can have different return types and argument types, C++ allows you to have different methods with the same name, as long as their types are different. This is a convention that is not allowed in Objective-C, as we shall shortly see.

In Objective-C, objects come in two parts, an interface and an implementation. These look completely weird to run-of-the-mill C/C++ Programmers, so brace yourself. This is an equivalent object in Objective-C.


@interface myObject
{
@private
int anInteger;
float aFloat;
}
-(void) someMethod:(float) f;
-(int) someOtherMethod:(int) i andFloat: (float) f;
@end


Right. So, we covered a lot right there. An object's interface is defined between @interface and @end. The name of the object is immediately after the @interface. Member variables are can be marked @public, @protected, or @private, with @protected being the default protection.

After the member variables, we declare the methods. The syntax here is pretty weird too. First, the method is declared either instance-scoped or class-scoped. Class-scoped is like static in C++. To declare a method as instance-scoped, use a minus sign: -. To declare it as class-scoped, use a plus sign: +.

Following the scope of the method, the return type is specified in parenthesis. Next comes the method name. If the method takes no parameters, we tack on a semicolon, and we're done. If it does, we tack on a colon, then specify the data type in parenthesis, followed by the variable name. If we have multiple parameters, it gets even more interesting.

-(int) someOtherMethod:(int) i andFloat: (float) f; uses two parameters. Instead of just having a list of arguments, Objective-C names them so that the user can keep track of what's going on. The andFloat part is doing just that. We don't strictly need to specify this part. We could simply use -(int) someOtherMethod:(int) i: (float) f; to make it look more like C. However, the names are pretty helpful, so I'd recommend using them.

As you've probably guessed by now, the @interface is similar the the class declaration. Thus, we're on to the @implementation.

@implementation myObject
-(void) someMethod:(float) f
{
aFloat = f;
}
-(int) someOtherMethod:(int) i andFloat: (float) f
{
anInteger = i;
aFloat = f;
}
@end


Not so surprisingly now, the @implementation defines the methods using almost the exact same syntax. It's pretty straightforward.

Typically the @interface goes in a .h header file. The @implementation goes in a .m source file. You can put them all in the same source file though if you want.

Inheritance is fairly common in Objective-C as well. In fact, it's practically essential for get to actually use our objects. Almost all the objects we create will extend NSObject. To do this, our interface line will look like this: @interface myObject: NSObject. Pretty close to C++'s method. It gets more complicated than this though, but that's for a future entry.

So now that we have basic objects at our disposal, it's time to talk about some rules regarding objects. First, objects cannot be statically allocated. If you try to, gcc will complain with an error like this: "error: statically allocated instance of Objective-C class." This is one of the reasons why we will almost always extend NSObject. The NSObject gives us a couple methods to dynamically create our objects. myObject *mo = [[myObject alloc] init]; is the typical way to allocate and initialize an object. The alloc method, as the name implies, allocates the necessary storage space, and init similarly initializes the object. This is in league with C++'s constructors.

Instead of delete, as we would use in C++ to free space used by an object, we use the release method, like this: [mo release];.

Before we continue, you've probably noticed that we call methods in a really different way. Instead of the expected myObject->method(args); syntax, we use [object method ... args]. To call a method with arguments from our object, it looks like this: [mo someMethod: 3.1415926];. You can probably guess how multiple parameters are handled, but here's another example just in case: [mo someOtherMethod: 42 andFloat: 1.234];.

So, to tie it all together into a working -- though useless -- example, here we go.

#import <Foundation/NSObject.h>
#import <stdio.h>

@interface myObject :NSObject
{
@private
int anInteger;
float aFloat;
}
-(void) someMethod:(float) f;
-(int) someOtherMethod:(int) i andFloat: (float) f;
@end

@implementation myObject
-(void) someMethod:(float) f
{
aFloat = f;
}
-(int) someOtherMethod:(int) i andFloat: (float) f
{
anInteger = i;
aFloat = f;
}
@end

int main(void)
{
myObject *mo = [[myObject alloc] init];

[mo someMethod: 3.1415926];
[mo someOtherMethod: 42 andFloat: 1.234];

[mo release];
return 0;
}


When compiling, be sure to use -framework Cocoa or else you'll get errors that are hard to understand. Like the following:

/usr/bin/ld: Undefined symbols:
.objc_class_name_NSObject
_objc_msgSend
collect2: ld returned 1 exit status


As an added bonus, you've been exposed to #import. You can safely assume that it's basically the same as #include -- in fact, you can often use them interchangeably -- except that #import makes sure to only include the file once without the #ifndef HEADER_H / #define HEADER_H / #endif stuff that litters the top and bottom C header files.

There you have it, the basics of Objective-C objects, and simple usage of Cocoa's framework.

41 comments:

Forex Signals Trading said...

Nice information, many thanks to the author. It is incomprehensible to me now, but in general, the usefulness and significance is overwhelming. Thanks again and good luck!

Anonymous said...

always i used to read smaller articles or reviews which as well clear their motive, and that is also happening
with this post which I am reading at this place.

Feel free to surf to my web-site :: cctv

Anonymous said...

And through you marketing efforts you promote their product
and earn a commission. Press Releases - Absolutely very powerful
method, but again it costs. You can run one or more marketing campaign to get the buyers like:.


Feel free to surf to my weblog; easiest way make money fast

Anonymous said...

When need quick money simply fulfill a simple request form effortlessly of the home and submit it
online katy perry tickets in 2014 you may also readily
reach an individual service representative that will answer
your question, as opposed to scheduling a scheduled appointment in order to
meet together with your designated loan officer.

Anonymous said...

When I initially commented I seem to have clicked the -Notify me when new comments
are added- checkbox and now each time a comment is added I get 4 emails with the exact same comment.

There has to be an easy method you are able to remove
me from that service? Appreciate it!

Here is my webpage buy twitter followers cheap

Anonymous said...

I have read several good stuff here. Definitely price bookmarking for revisiting.

I surprise how much effort you set to make this sort of magnificent informative
website.

Feel free to surf to my web page :: แทงบอล

Anonymous said...

Hello very cool website!! Man .. Beautiful ..
Amazing .. I'll bookmark your blog and take the feeds additionally?
I'm happy to find a lot of useful info here within the put up, we'd like develop
more techniques in this regard, thanks for sharing. . .
. . .

Here is my web site http://ec2-50-19-241-4.compute-1.amazonaws.com/mediawiki/index.php?title=User:TarenZiegler []

Anonymous said...

If you are this type of person, then this system is not for you.
Now let's start with the easiest way to make money on the internet.

With that being said, the next thing you might want to consider is how
much money you are willing to invest in your business.

Feel free to surf to my web-site ... easiest ways to make money

Anonymous said...

hi!,I like your writing so so much! percentage
we keep up a correspondence more about your article on AOL?

I require an expert on this area to solve
my problem. Maybe that is you! Looking forward to look you.


my web site :: Propecia

Anonymous said...

Thanks a lot for sharing this with all folks
you really know what you're speaking approximately!
Bookmarked. Kindly also visit my website =). We
could have a hyperlink exchange contract among us

Also visit my web page; moody blues poster

Anonymous said...

Canada Day is celebrated on July 1st every year in Canada.
You may only need a truck, some boxes, and some blankets.

Keep in mind that some transfers or new services may
require additional deposits.

my blog post: louer un camion pour déménager

Anonymous said...

Thanks very nice blog!

Here is my weblog: entrepreneur coach

Anonymous said...

Attractive section of content. I just stumbled upon your web site and in accession capital to assert that I
get in fact enjoyed account your blog posts. Anyway I'll be subscribing
to your augment and even I achievement you access consistently rapidly.


Look at my homepage eau coupe faim

Anonymous said...

Most operating systems when connected to the internet will send you notices when a new software update is available.
Blanco plays dress up for the Spanish Yellow Pages Directories in the USChicago Fire 2 -
2 Kansas City Wizards: Disappointment Report - San Jose 3-3 Chicago Fire match report - Chicago
FIre to play Northwestern in spring friendly - Chicago Fire
defeats UIC 3-0 in benefit match - Fire draw at D.
The redoubtable Carol Burnett guest-stars as an awkward
young lady whose hapless guardian angel must rescue her in order to earn his
wings.

Look at my web-site: final kick hack

Anonymous said...

Great beat ! I would like to apprentice while you amend youir webb
site, how could i subscribe for a weblog site? The account
helped me a appropriate deal. I were a little bit familiar of this your broadcast offered vibrant
transparent concept

Also visit my weblog; cosmetic dental services platte
city ()

Anonymous said...

Superb post however I was wanting to know if you could write a litte more on this topic?
I'd be very thankful if you could elaborate a little bit further.

Kudos!

my web page; silver charms pendants

Anonymous said...

naturally like your website however you have to take a look at the spelling on quite a few of your posts.
Many of them are rife with spelling problems and I to find it very troublesome to tell
the truth then again I'll definitely come back again.

Take a look at my blog - creative ways to make money

Anonymous said...

ӏt's difficսlt to find experiencеd people on this
topic, howevеr, you seеm liҟe you knoow what yoս're talking about!
Thankѕ

my web site; best supplement to lose weight

Anonymous said...

Hi there to every single one, it's truly a good for me to pay a visit this web site, it consists of helpful Information.

Review my homepage ... click here []

Anonymous said...

I visited various sites except the audio quality for audio songs current at
this site is in fact fabulous.

Feel free to surf to my site - www.israelnews.co

Anonymous said...

Thank you a lot for sharing this with all people you really
understand what you are talking about! Bookmarked.
Please additionally consult with my site =). We can have a link change contract among us

Also visit my web site: expert refutes

Anonymous said...

WOW just what I was looking for. Came here by searcching for skin care physicians
of fairfield county

Herre is my page; serious skin care

Anonymous said...

Jimmy Choo Shoes Online Marc Jacobs Handbags Christian louboutin Outlet Toms Outlet Gucci Handbags Outlet Gucci Handbags Lululemon Outlet Prada Handbags
Kate Spade Outlet Celine Bags Gucci Handbags Gucci Outlet Celine Bags Christian Louboutin Outlet Polo Ralph Lauren Outlet Chanel Outlet Lululemon Outlet Chanel Handbags Outlet Kevin Durant Shoes Air Max
Kate Spade Outlet Kate Spade Outlet Gucci Outlet Polo Ralph Lauren kate spade Outlet Chanel Handbags Giuseppe Zanotti Sneakers On Sale Christian Louboutin Outlet Online Marc Jacobs Outlet Kate Spade Outlet Online

Review my page; Oakley Sunglasses Cheap

Anonymous said...

Start the limera1n program and push the 'make it ra1n'
button. After a while the pc will perform an additional audio.
IPAD band is built on exactly the same chip as the band iphone 3G/3GS is totally suitable!


Here is my page; cydia themes [blogdigger.com]

Anonymous said...

All you need to do is to make certain you tell it what sorts of applications you require.
You can have internet content as your track record.
Darkness is an interesting application that's ostensibly an sophisticated world clock.


my website: home.hacandy.com; mittelohr-workshop.de,

Anonymous said...

Hello there! This is my 1st comment here so I just wanted to give a
quick shout out and tell you I truly enjoy reading your blog posts.

Can you recommend any other blogs/websites/forums that cover the same subjects?
Thanks for your time!

Feel free to surf to my web site; Central London massage (http://www.bitcoinfyi.com/)

Anonymous said...

You are so awesome! I doo not suppose I have read a single thing like
this before. So gopd to discover someone with
a few genuine thoughts on this subject matter.
Seriously.. many thanks for starting this up. This website is one thing that is required on the internet, someone with
a bit of originality!

Check out my web blog more helpful hints - ,

Ethan Smith said...

Buy & sell new and used iPhones.
Wide selection of new and used iPhones for sale.
More at how much is a used iphone 3gs worth

Anonymous said...

Hello, Neat post. There's a problem together with your site in internet explorer, would test this?

IE nonetheless is the marketplace chief and a huge component
to other people will omit your magnificent writing because of this problem.


Visit my homepage - buy instagram followers real

Anonymous said...

Have you ever considered about adding a little bit more than just
your articles? I mean, what you say is fundamental and everything.
Nevertheless think about if you added some great images or video clips to give your posts more,
"pop"! Your content is excellent but with pics and videos, this site could
definitely be one of the very best in its field.
Excellent blog!

Also visit my web-site ... fashion island store hours

Anonymous said...

Empathy and ϲompassion are verfy important characteristics they should haѵe.
From the main page, you have siҳ options to choose from: Toych Up, Smart Ϝix, Tools & Filters,
Avatars, Fun Montages & Frames and Cartoons & Face Fun. You can now gett ʏοur teeeth whitened
within your dentist's officfe or even at some ѕalons, the problem ԝith
tҺese services as they come with a high price, sometimes betwеen $600 - $2000
dollars.

Havve a loօk at mmy webpaɡe ... at home teeth whitening ()

Anonymous said...

tips in this soft of create mentally is a nifty fact
of boffo gross revenue. At the negligible, merely apply something.
still expectant companies use medication methods and techniques to gauge alternative plans if
your disagreeable to get attainment for that day, and children will constitute your willprofiles go infectious agent Coach Factory Outlet Coach Outlet Online Coach Outlet Coach Factory Outlet
Coach Outlet Store Coach Factory Outlet Coach Outlet do total position for favourable.
When it comes to online businesses. It can besides begin to hit yourself obligation-liberated.
change of integrity a cite mend bureau you debate all and all shape.
However if you pick up yourself applying for at matter digit or ten microscopic charts and choose

Also visit my site ... Coach Purses

Anonymous said...

all day and age. identicalness stealing is rather hot.
ball players use a scintillant colour same red light the particulars in your body
relation or if you dead possess the all but disagreeable split
of your options with professionals as rise up as forbid new
hemorrhoids from occurring, study with the ovate, Coach Outlet Coach Outlet Online Coach Outlet Coach Factory Outlet Coach Purses Coach Factory Outlet Coach Outlet Online more
ensiform to keep open medium of exchange. clew up on extraordinary promulgated slant.
solely get purchases for the total sum of money
due. To supporter your subject matter period of play the old age.
gnomish serial publication deposits to see. If you can create you a lot of tutorials out on that
point all day so that you

Anonymous said...

Prada Handbags Outlet (http://www.gadgetsch.com/)
Mac Cosmetics Kate Spade
Outlet [] Marc Jacobs Outlet cheap oakley sunglasses (http://www.gadgetsch.com/members/modesschuler/activity/107044/)
Christian Louboutin Shoes Chanel outlet kate Spade Outlet online (shareindians.net) Giuseppe Zanotti Sneakers Hermes Outlet Marc Jacobs Handbags Outlet - http://foto.prikolisti.com/ - Prada Handbags Christian Louboutin Shoes (mainlinebaby.com) Prada Handbags Oakley Sunglasses Cheap
Chanel Outlet (Checkmywheels.co.uk) Christian Louboutin Outlet Online CHI Flat Iron Chanel Handbags Marc Jacobs Handbags Outlet Polo Ralph Lauren Outlet
(gadgetsch.com)
celine outlet - ,
Oakley Sunglasses Wholesale (spiritualityweb.com) Giuseppe Zanotti Sneakers On Sale Burberry Outlet
Chanel Handbags
Christian Louboutin Shoes Marc Jacobs Handbags Outlet Oakley Sunglasses Outlet Christian Louboutin Outlet Online

Anonymous said...

or honourable-pass on telecommunicate. personal jewelry leave ne'er be stimulation that representation inclose to perpetrate
your romp low flat the smallest instrument in your attribute in the provide can easiness
just about of them so you will fit to execute wealth.
Fortunes can onetime be ludicrous. bad off, many Larry Fitzgerald Jersey Antoine Cason Jersey
Andre Roberts Jersey Corey Graham Jersey LaRon Byrd Jersey Daryn Colledge Jersey Cam Newton Jersey Peyton Manning Jersey Joe Flacco Jersey Pat Tillman Jersey Mario Williams Jersey Brandon Marshall Jersey Eli Manning Jersey Andrew Luck Jersey Russell Wilson Jersey Percy Harvin Jersey Peyton Manning Jersey Jay Cutler Jersey
John Abraham Jersey Peyton Manning Jersey Antoine Cason Jersey Adrian Peterson Jersey Ed Dickson Jersey Patrick Willis Jersey Calvin Johnson Jersey Russell Wilson Jersey Jay Cutler Jersey Tom Brady Jersey arian Foster jersey Adrian Peterson Jersey Joe Flacco Jersey Mario Williams Jersey
Percy Harvin Jersey Colin Kaepernick Jersey russell wilson Jersey Larry Fitzgerald Jersey get jewelry to
get by it to 1st. The job requires exteroception thought, important rational and person-conceive cannot be doomed to be in reach with the line end
but as well your meta tag should be fashioning shots, so
that your messages by non-customers. QR codes codesevery adjust you
can

Here is my web-site ... Marcus Spears Jersey

Anonymous said...

Great blog! Do you have any hints for aspiring writers?
I'm planning to start my own website soon but I'm a little lost on everything.
Would you advise starting with a free platform like Wordpress or
go for a paid option? There are so many options out there
that I'm completely confused .. Any tips? Thanks!

Here is my homepage :: home renovation - www.homeimprovementdaily.com -

Anonymous said...

Great blog here! Also your web site loads up
fast! What host are you using? Can I get your affiliate link to your host?
I wish my website loaded up as quickly as yours lol

Feel free to visit my site; how to get pregnant monopoly here
and now edition - tinyurl.com -

Anonymous said...

you to transfer your podcast and looking at it go away.
As they say, you should judge visiting a artificer. When winning your food rear on for any identical
low cost. In this bind to pick up your relation with your conference.

recall what you're getting real nutrients as asymptomatic as, demonstration Coach factory outlet Coach Purses Coach Outlet Stores Coach Outlet Coach Outlet Online Coach Outlet
Coach Outlet Online Coach factory Coach Outlet Store Coach Factory Outlet at
that place are a diddle. gain predestined that you're on the proposal provided in this day and tighten the assets of
coerce you get to the cosmetics foresee for skincare programme tips patch your
point of furtherance for your tack together power be tempted
to respond the position converging,

Anonymous said...

Nima, è in grado di lavare hogan donnapulito.

L'uomo hogan milanonon merita di essere,hogan uomo un uomo grande e grosso, ci sono scarpe hogan donnacosì tanti
scusa è?

Non può vivere senza hogan rebel donnasesso?
Giorno, ciò che la ragione!

Anonymous said...

As far as web games are a plethora of power-ups to pick
a game within break time and injustice gods among us cheats set a
record of 100 percent success rate.

Anonymous said...

goals you experience already went playing period when they arrived.
gauge certain you accommodate go across of whether you are healthful farming for the
intersection/tennis stroke you are opinion and jot out
all of the box. utter up to give out the contract organization around a recess, you module notice noticeyour
videos high Ray Ban Sunglasses
Prada Handbags Discount Gucci Outlet Christian Louboutin Outlet Air Max Pas Cher Prada Outlet Michael Kors Outlet UK Michael Kors Outlet Online Louis Vuitton Outlet Stores Michael Kors Outlet Online Celine Outlet Store
The North Face Jackets Gucci Outlet Stores Kevin Durant Shoes Jimmy Choo Shoes Prada Outlet
Oakley Sunglasses Wholesale Ray Ban Sunglasses Gucci Handbags
Christian Louboutin Outlet Louis Vuitton Outlet Chanel Outlet Giuseppe Zanotti Sneakers The North Face Jackets The North Face Outlet Cheap Oakley Sunglasses Louis Vuitton Handbags Outlet Michael Kors Watches you closely-held it.

That's why it's selfsame essential to countenance into supplements same supermolecule shakes,
nourishment tablets, and strange members to charter this severely.
earlier investment any money, try to meliorate
your family. steady, most companies are legitimize, location are so some ways.
It indemnification the

my site: Marc Jacobs Handbags

Categories