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.

26 comments:

  1. 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!

    ReplyDelete
  2. 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

    ReplyDelete
  3. 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

    ReplyDelete
  4. 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.

    ReplyDelete
  5. 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

    ReplyDelete
  6. 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 :: แทงบอล

    ReplyDelete
  7. 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 []

    ReplyDelete
  8. 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

    ReplyDelete
  9. 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

    ReplyDelete
  10. 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

    ReplyDelete
  11. 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

    ReplyDelete
  12. 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

    ReplyDelete
  13. 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

    ReplyDelete
  14. 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

    ReplyDelete
  15. 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

    ReplyDelete
  16. 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

    ReplyDelete
  17. 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

    ReplyDelete
  18. 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 ()

    ReplyDelete
  19. 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 -

    ReplyDelete
  20. 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 -

    ReplyDelete
  21. 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!

    ReplyDelete
  22. This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.
    One Machine Learning
    One data science
    Bissi.Global

    ReplyDelete