Users Pricing

articles

home / developersection / articles / objective-c : programming language summary

Objective-C : Programming Language Summary

Tarun Kumar 3843 09 Jul 2015 Updated 13 May 2026

Previouslywe seen the Overview of Objective C: Objective C : Overview

 

Objective-Cis an extension to C
  • AnyC code will work in an Objective-C program.
  • Cdata types and pointers are used in Objective-C and Cocoa programming.
  • Cconventions are still used.
  • E.g.The main method is where program execution begins, and returns an int.
WritingObjective-C Programs
  • Codeis saved in .m files, e.g. “HelloWorld.m” – ‘m’ originally stood for‘messages’.
  • #import<Directory/Example.h>
    • Pre-processor“import” statement means that this will only be included once. It means youdon’t have to use #ifdef couples with #include.
  • NSLog()is similar to printf(), but is more advanced.
    • Itautomatically adds the end-line character.
    • Mustbe passed an NSString.
    • TheNSString may take the standard formatters, including %d, and introducing %@ foran object. When the %@ is reached, the corresponding object’s descriptionmethod is called, which should return an NSString.

 

NewData Types
  • BOOL
    • Storesa boolean value as “YES” or “NO”.
    • Pre-datesC’s bool type by a decade.
    • BOOLis just a typedef for a signed character (which uses 8 bits). Only thelast bit determines the value of BOOL).
  • id
    • Canhold a pointer to any type of object.
  • NSString
    • NSStringliteral can be referenced using the @ shorthand. For example, “NSString message= @”Hello World!”;”
  • NSArray(an enhanced array that supports objects )
    • Canbe traversed quickly using “for in”.
    • e.g.“for (NSString * string in array) { // do something }” 
Classesand Objects


  • Definedusing two sections, which make up a class (the interface and the implementation).These sections are normally implemented in two separate files, a .h (header)file for the interface, and a .m (source code) file for theimplementation. The implementation imports the header file.
  • Headerfiles are referred to as ‘interface files’ and source code files are referredto as ‘implementation files’.
  • Interface: The interface of a class is usually defined in a header file. A commonconvention is to name the header file after the name of the class, e.g. Ball.h would contain the interface forthe class Ball.
  • Implementation: The interface only declares the class interface and not the methodsthemselves: the actual code is written in the implementation file.Implementation (method) files normally have the file extension .m, whichoriginally signified "messages"
    • Alwaysreference objects by using pointers.
    • Sendingobjects messages – i.e. calling methods.
    • Doneusing square brackets.
    • E.g.“[goodBook setTitle: popularTitle];”
    • Where‘goodBook’ is an instance of a class, say, Book, setTitle is aninstance method of the class Book, and ‘popularTitle’ is a variable thatis of the type requested by the method setTitle.
    • Amethod call (message send) can be made to any object. This is known as dynamictyping, and has the advantage that types can be unknown at compile time,but runs the risk of run-time errors, should a message be sent to an objectthat doesn’t have such a method within it. At the time of writing, myunderstanding of this is that exception handling must be put into place ifthere’s a possibility that the object won’t have the method.
  • Instantiating objects: Once anObjective-C class is written, it can be instantiated. This is done by firstallocating an uninitialized instance of the class (an object) and then byinitializing it. An object is not fully functional until both steps have beencompleted.
  • @class
    • Isused to set up a forward reference (or forward declaration),which tells the compiler that such a class does exist, and that it’llfind out about it in the future.
    • Exampleuse: if a Class is composed of another class (or classes). Usethe @class before the @interface declaration in order to let the compiler knowit’ll find out more later.
    • e.g“@class Brick;”
    •  However,if more than just the class name is being used (e.g. instance variables ormethods), then that class must be imported.
Properties
    • Introducedin Objective-C 2.0
    • @property(parameters) <TYPE> <variable name>;
    • Usedin the @interface section.
    • INCOMPLETENOTES
    • @synthesize
    • Usedin the @implementation section. This automatically creates methods as required(stated in the corresponding @property).
  • Copying/DuplicatingObjects
    • See‘NSCopying’ under protocols.

 


Objective-CRuntime:
  • Creates an object for each class, known as a class object.
  • This object holds pointers to the superclass, class name, class methods, and holds a long which specifies how much memory needs to be allocated to store an instance of the class. 

Message/MethodDispatch System:
  • Partof the Objective-C runtime code.
  • Amessage is sent using square brackets [ and ] as follows:
  • “[boat sailFromShoreTo: america ];”
  • Themessage is sent to the object boat, which is of type Boat, so the message goesto the class to look up the method sailFromShoreTo. If this method isnot found in Boat, then the dispatch system moves to the superclass, andsearches for the method there.
  • Ifthe dispatch system reaches the highest object in the hierarchy and stilldoesn’t find, then some serious problems may occur..

MemoryManagement:
  • Cocoauses reference counting (also known as retain counting).
  • Everyobject has an integer reference count (also know as a retain count).
  • Whencode wants to use an object it increments the retain count, and when it’sfinished with it, it decrements it.
  • Whenthe retrain count reaches 0 the object is destroyed using dealloc(Objective-C will do this, don’t ever call this directly).
  • Objectscreated using alloc, new or copy have a retrain count of1.
  • retain– increments the retain count. Returns a pointer to the object so you can chainmessage sends.
  • release– decrements the retain count. Void method.
  • retainCount– returns the retain count.
  • Objectownership – when code starts using an object it should retain it, andrelease it when it’s finished using it.
  • Mutatormethods – one way of handling memory management when setting an object incomposition is to – retrain the new object, then release the old, then set.
  • Autoreleasepool
  • NSAutoreleasePool
  • Acollection of objects that automatically get released.
  • autorelease– puts an object into an NSAutoreleasePool.
  • Whenthe pool is destroyed (using release to get to a retain count of 0), itsends release messages to all the objects in the pool.
  • drain– empties the pool (releases all the objects) without destroying the pool.
  • Whenyou create an NSAutoreleasePool, it becomes the default pool all the objects gointo.
CocoaMemory Management Rules:
  • Anewly created object (an object created using the alloc, copy or new methods)has a retrain count of 1. The programmer is responsible for cleaning up thisobject.
  • Retrievingan object via another mechanism – assume it has a retain count of 1 and is setto autorelease. Retain and release it if you’re going to use it for a while.
  • Alwaysbalance retains and releases.
  •  Garbagecollection
  • Ispossible since Objective-C 2.0. Just needs to be enabled on the compiler.
  • Onceenabled, all the memory management instructions are just ignored and thegarbage collector is used.
  • Garbagecollection can’t be used on the iPhone. 
Formal Protocols:
  • Definition:
    • Anamed list of methods.
    • Whenadopting a protocol, you’re agreeing to supply these methods (and have tootherwise you’ll get a compiler error).
    • Similarto Java interfaces.
  • Howto adopt a protocol:
    • Thisis done in the @interface section of the class, using the following format:
    • @interfaceclassName : Subclass <adoptsThisProtocol, andThisProtocol>
    • Thename of the protocol you wish to adopt follows within matching < and >.Multiple protocols are separated by commas.
    • Protocolsare inherited.
  • Declaringprotocols:
    • @protocol<NAME>
      • Starta protocol definition with this declaration.
      • Musthave a unique name.
      • Defineas many methods as necessary using the usual method declaration rules. Thesemethods will need to be implemented by a class that adopts this protocol.
  • @optional
    • Objective-C2.0
    • Usedbefore declaring methods that a class can optionally implement.
    • @required
    • Objective-C2.0
    • Usedbefore declaring methods that a class has to implement.
    • @end
    • Endsthe definition of the protocol.
Usingprotocols with data types:
  • Protocolscan be used to specify objects.
  • Thisis achieved using the id data type, followed by the protocols that have to beimplemented. For example:
  • “-(void) methodName: (id<NSCopying>) objectName “.
  • Thismethod will take any object that implements the NSCopying protocol, if itdoesn’t implement this protocol, the complier will give a warning.
Example/UsefulProtocols:
  • NSCopying
  • Declaresthe following method:
  • ”– (id) copyWithZone: (NSZone *) zone ”
  • Themethod copy deals with the NSZone and calls this method. When using thiscopy method, send the copy message.
  • The(NSZone *) parameter comes from old Objective-C programming. An NSZone is alocation in memory that can be used for the copying (I think).
  • Deepcopy implementation for a class:
  • Makea pointer to a class.
  • Makethis pointer point to [[[self class] allocWithZone: zone] init];
  • Themethod class returns the class of the current object. If this class isextended then the copy method will still work correctly.
  • Themethod allocWithZone allocates memory for a new object (like alloc)using an NSZone provided.
  • Themethod init is called to initialises the object.
  • Aspecific initialiser method can be used, passing it the values of theobject-to-be-copied to initialise with.
  • Orsetters can be used to make the new object the same as the old one.
  • The. operator can be used to access any variable. A copy method can make good,appropriate use of this operator.
  • Returnthe pointer originally made. (This object has a retain count of 1 due to the allocWithZonemethod).
  • Forsubclasses, call [super copyWithZone: zone] before doing subclassspecific copying instead of calling [[self class] allocWithZone:zone] init ].

 Next, wewill learn about: Objective C : Headers, Interfaces, Methods


Tarun Kumar

Other