NOTIFICATION: These examples are provided for educational purposes. Using this code is under your own responsibility and risk. The code is given ‘as is’. I do not take responsibilities of how they are used.

This tutorial assume that you have some experience with C++ and concepts of Programming Languages.

Basic differences between objective-C and C++:

  1. Keywords begin with the @ character, for example: @class, @try, @catch, etc.
  2. Boolean type is BOOL (instead of bool as in C++). They can be set as YES or NO
  3. Every object is of type id
  4. Classes:
    1. They are objects.
    2. They are instances of a meta-class (root class).
      1. This means that they can be dynamically managed
    3. You can create instances base on the name class
    4. Add classes at run-time
    5. Ask methods from the class
    6. Equivalent to C++ Run-Time Type Information (RTTI) but more powerful and with out the lack of portability issues related with RTTI.
    7. Objective-C defines a root class, NSObject. Every new class should be derived from this class.
    8. Since classes are meta-class instances (objects), it is possible to declare a pointer to them.
  5. nil is the equivalent of NULL in C++ for an object pointer; however, do not interchange nil and NULL
  6. The equivalent of nil for a class pointer is Nil.
  7. Interface code of a class goes in .h files
  8. Implementation code of a class goes in .m files
  9. Implementation code of a class in Objective-C/C++ goes in .mm files
  10. Directive #import replace directive #include.
    1. The directive #importinclude already the compilation guards normally used in C++, example:
      #ifdef COMPILATION_GUARD_H
      #define COMPILATION_GUARD_H
      ...
      /* code */
      ...
      #endif // COMPILATION_GUARD_H
  11. As standard, all class names begin with the prefix NS, example: NSString
  12. Calling a method is done by using the following syntax:
    [my_object do_something]

    instead of using this syntax as in C++:

    my_object.do_something();
  13. Objects:
    1. All of them should be of type NSObject
    2. Every pointer to an object should be declared as NSObject*
      1. Using type id is a short way to declare a pointer to an object plus it provides with a dynamic-type checking
    3. Null object pointers should be set to nil (instead of NULL as in C++)
  14. Instance data are the equivalent to attributes in C++.
  15. Methods are the equivalent to member functions in C++.
  16. Instances data and Methods cannot be mixed as they are in C++
    1. Attributes are declared in braces while their implementation lies inside the @implementation block.
      1. This allow the implementation of some methods without being exposed in the interface
    2. The prefix “” indicate instance methods while the prefix “+” indicate a class method (staticin C++).
      1. These prefixes should not be confused with private and public keywords of C++.
      2. These prefixes have nothing to do with UML “-” and “+” symbols
    3. Type of parameters are enclosed in parenthesis ()
      1. Parameters are separated with colons “:
    4. @interface keywords is the equivalent to the class keyword in C++
      1. Do not confuse with @class keyword which is used only for forward declarations
    5. Example:
      1. In C++:
        class Base{
          private:
            int value;
          public:
            int getValue();
            void setValue(int new_value);
        };
        ...
        int Base::getValue(){  return value; }
        void Base::setValue(int new_value){ value = new_value; }
      2. In Objective-C:
        @interface Base : NSObject{
          int value;
        }
        -(int) getValue;
        -(void) setValueFrownint) new_value;
        @end
        
        @implementation Base
        -(int) getValue { return value; }
        -(void) setValueFrownint) new_value{ value = new_value;}
        @end
  17. Forward declarations in Objective-C are done by using the keyword @class
    1. @protocol keyword can be also being used
    2. Example:
      1. Forward declaration in C++:
        // car.h
        #ifndef CARLSTEIN_CAR_H
        #define CARLSTEIN_CAR_H
        
        class Motor; // Forward declaration
        class Car{
          private:
            Motor *motor;
          public:
            void start();
        };
        void Car::start() { ... }
        #endif // CARLSTEIN_CAR_H
      2. Forward declaration in Objective-C:
        // car.h
        @class NSMotor; // Forward declaration
        @interface NSCar : NSObject{
          NSMotor *motor;
        }
        -(void) start;
        @end
        @implementation NSCar
        -(void) start {...}
        @end
  18. Public, private and protected:
    1. In C++, attributes and methods can be public, private (default mode), and protected.
    2. In Objective-C, methods can only be public.
      1. However, it is possible to ‘mimic’ the private mode for methods by declaring these methods inside @implementation without declaring them inside @interface.
        1. Using this trick make the methods less exposed but they can still being called.
    3. Instance data can be public, private, and protected (default mode).
    4. Inheritance can only be public, it cannot be tagged as public, private, or protected.
    5. Example:
      1. In C++:
        class Car{
          private:
            Motor *motor;
            void start_computer();
          public:
            Accessory *accessory;
            void start();
          protected:
            ExternalSensor *ext_sensor;
            void check_sensors(int number, char type);
        };
      2. In Objective-C:
        @interface Car : NSObject
        {
          @private:
            NSMotor *motor;
        
          @public:
            NSAccesory *accessory;
        
          @protected:
            ExternalSensor *ext_sensor;
        }
        
        -(void) start_computer;
        -(void) start;
        -(void) check_sensors : (int) number : (char) type;
        
        @end
  19. As you can see in the previous example:
    1. The return type of a method is enclosed by parenthesis ()
    2. All parameters are separated by colons “:
    3. ” prefix is to indicate an instance method
    4. +” prefix is to indicate a class method (static in C++)
    5. Remember that methods are always public
  20. Declaring a class data attribute such as staticin C++ is not possible; however, we can be ‘mimic’ it:
    1. In the implementation file, use a global variable.
    2. By using accessors on it, the class can use the variable with class methods or normal methods.
    3. In the initialize method of the class, the variable can be initialized.
  21. When working with prototypes, calls, instance methods and class methods have in consideration:
    1. The return type of a method is enclosed by parenthesis ()
    2. Parameters are separated by colons “:
    3. Method’s name and attribute’s name can be the same (normally this is use for creating getters)
      1. A label can be associated with parameters. This label is a name specified before the colon “:” and become part of the name of the method plus modifies it.
      2. The first parameter must not have a label since the name of the method is already the label.
    4. In Objective-C, we do not say that we call a method but that we send a message to the method.
    5. Example:
      1. In C++:
        //prototype
        class Base{
         ...
         insertObjectAt(void *, size_t);
        }
        ...
        void Base::insertObjectAt(void *obj, size_t index)
        ...
        Base shelf;
        shelf.insertObjectAt(new_object, 9);
      2. In Objective-C:
        1. Without using label:
          @interface Base : NSObject{
          ...
          }
          ...
          //prototype
          -(void) insertObjectAtFrownid)objFrownsize_t)index
          @end
          ...
          Base shelf;
          [shelf insertObjectAt:new_object:9];
        2. With using label:
          @instance Base : NSObject{
          ...
          }
          ...
          //prototype.
          -(void) insertObjectFrownid)obj atIndexFrownsize_t)index
          @end
          ...
          Base shelf;
          // This is easier to read
          [shelf insertObject:new_object atIndex:9]; // This WORKS!
          // This fails plus it is not easier to read
          [shelf insertObject:new_object:9];         // This FAILS!
  22. self keyword is the equivalent of thiskeyword of C++
    1. Unlike this keyword in C++, self is not a real keyword and its value can be changed (useful in constructors).
    2. self is a hidden parameter which each method receives. The value of this hidden parameter is normally the current object.
    3. Example:
    4. In C++:
      class Point {
        private:
          int x;
          int y;
        public:
          void setInterceptY(int new_y);
      };
      
      void Point::setInterceptY(int new_y) {
        x = 1;
        int y;
        ...
        y = new_y >> 1; // local y
        ...
        this->y = y;    // object's y
      }
    5. In Objective-C:
      @interface Point : NSObject
      {
        int x;
        int y;
      }
      -(void) setInterceptY : (int) new_y;
      @end
      
      @implementation Point
      -(void) setInterceptY : (int) new_y {
        x = 1;
        int y;
        ...
        y = new_y >> 1; // local y
        ...
        self->y = y;    // object's y
      }
      @end

© 2011, Alejandro G. Carlstein Ramos Mejia. All rights reserved.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

*

Click to Insert Smiley

SmileBig SmileGrinLaughFrownBig FrownCryNeutralWinkKissRazzChicCoolAngryReally AngryConfusedQuestionThinkingPainShockYesNoLOLSillyBeautyLashesCuteShyBlushKissedIn LoveDroolGiggleSnickerHeh!SmirkWiltWeepIDKStruggleSide FrownDazedHypnotizedSweatEek!Roll EyesSarcasmDisdainSmugMoney MouthFoot in MouthShut MouthQuietShameBeat UpMeanEvil GrinGrit TeethShoutPissed OffReally PissedMad RazzDrunken RazzSickYawnSleepyDanceClapJumpHandshakeHigh FiveHug LeftHug RightKiss BlowKissingByeGo AwayCall MeOn the PhoneSecretMeetingWavingStopTime OutTalk to the HandLoserLyingDOH!Fingers CrossedWaitingSuspenseTremblePrayWorshipStarvingEatVictoryCurseAlienAngelClownCowboyCyclopsDevilDoctorFemale FighterMale FighterMohawkMusicNerdPartyPirateSkywalkerSnowmanSoldierVampireZombie KillerGhostSkeletonBunnyCatCat 2ChickChickenChicken 2CowCow 2DogDog 2DuckGoatHippoKoalaLionMonkeyMonkey 2MousePandaPigPig 2SheepSheep 2ReindeerSnailTigerTurtleBeerDrinkLiquorCoffeeCakePizzaWatermelonBowlPlateCanFemaleMaleHeartBroken HeartRoseDead RosePeaceYin YangUS FlagMoonStarSunCloudyRainThunderUmbrellaRainbowMusic NoteAirplaneCarIslandAnnouncebrbMailCellPhoneCameraFilmTVClockLampSearchCoinsComputerConsolePresentSoccerCloverPumpkinBombHammerKnifeHandcuffsPillPoopCigarette