Cocoa, Objective C Questions & Answers

All the questions and answers given below are created based on experience while working and referring to Apple Developer Site.

1. What is Cocoa

Cocoa is an application environment and a suite of object oriented components to develop OSX and iOS Apps.
Cocoa apps are primarily developed using Objective C language. Objective C is based out of ANSI C thus ANSI C code can be mixed with Objective C code while developing a Cocoa Application.
Cocoa Applications can also include C++ code.
Cocoa has 3 core frameworks

  • Foundation Framework (Part of the core service layer)
  • App Kit Framework (Application Frameworks)
  • Core Data Framework.

2. What does Cocoa Offer?

  • Cocoa provides the infrastructure for event driven behavior.
  • It helps manage application, windows and workspaces
  • Has a rich library of user interface objects available in Interface builder. UI Objects can be dragged dropped from the interface builder or can be created from code. Some sample UI objects are (buttons, tables, views, windows, panels, drawers, segmented control etc).
  • Supports drawing and imaging
  • Supports interaction with file system and workspaces
  • Supports concurrency, multithreading , lazy loading etc
  • Supports internationalization
  • Supports different text representation
  • Maintains application preferences
  • Support networking, communication with servers
  • Printing support, basic printing to advanced printing options such as pagination and content formatting
  • Handles Undo and Redo management
  • Supports Audio and Video using Quicktime framework
  • Support data exchange using Copy Paste and Drag Drop
  • Support document based architecture (similar to word or excel)
  • Supports script-ability, i.e Applications responding to commands emitted from Apple Scripts (e.g: Play, Pause songs in iTunes using Apple Scripts)

3. What are the different Layers of the Mac OSX?

The Mac OSX is layered into the following
–       User Experience

  • Aqua
  • Dashboard
  • Spotlight
  • Accessibility

–       Application Frameworks

  • Carbon
  • Java
  • Appkit

–       Graphics and Media (Application Services)

  • Core Animation
  • Core Image
  • Core Video
  • Quicktime
  • OpenGL
  • Quartz
  • Core Audio

–       Core Services

  • Carbon Core
  • Launch Services
  • Core Foundation
  • Foundation

–       Darwin

4. What are the main development Environment for Cocoa?

Xcode and Interface Builder (For UI Development using drag and drop from an object library)
However applications can be built using a text editor and building the application from command line using makefiles and use the gdb debugger to debug the application from command line
Using Xcode and Interface builder it is very easy to design, manage, build and debug software products

5. What is Xcode?

Xcode is the engine that powers Apple’s integrated development environment (IDE) for OSX and iOS
Using Xcode developers can

  • Create and Manage Projects,
  • Specify platforms and targets, Dependencies and Build Configurations
  • Build the project
  • Debug the project
  • Can build code written in C, C++, Objective C
  • Create graphic user interface.
  • Manage Source Code using subversion

6. What are the compiling options in Xcode?

  • GCC – The GNC C Compiler (gcc)
  • LLVM – GCC (Low level virtual machine compiler. Provides past optimization times.
  • Clang – Fast compile times and diagnostics

7. What is Interface Builder?

Interface builder is a graphical tool for creating user interfaces
Has the following design elements

  • Nib Files /XIB files – contains the objects appearing on a user interface in an archived form
  • Object Library – Contains a list of UI Objects.
  • Inspector – Used for configuring the objects of a user interface
  • Connection Panel – connects outlets to actions.

8. What are the performance tools?

  • Instruments – to show CPU Usage, Disk Reads and Writes, Memory Statistics, thread activity, network statistics etc
  • Shark – Traces function calls and graphs memory allocation
  • BigTop – graphs performance trends
  • Spin Control – Gathers information about what the application was doing when the rainbow spinner appeared
  • Mallod Debug- Shows how much memory the application is consuming and which functions allocated large amounts of memory. Also helps find leaks by finding allocated memory that is not referenced anywhere in the program
  • QuartzDebug – helps debug applications that do large amounts of drawing and imaging

9. Cocoa Frameworks

There are two main frameworks required for building Cocoa Applications
Mac OSX – AppKit Framework and Foundation Framework
iOS Apps – UIKit Framework and Foundation Framework

10. Details about the Foundation Framework

The Foundation framework defines a base layer of classes that can be used for any type of Cocoa program.
Foundation framework is designed for

  • Define basic object behavior and introduce consistent conventions for such things as memory management, object mutability, and notifications.
  • Support internationalization and localization with (among other things) bundle technology and Unicode strings.
  • Support object persistence.
  • Support object distribution.
  • Provide some measure of operating-system independence to support portability.
  • Provide object wrappers or equivalents for programmatic primitives, such as numeric values, strings, and collections. It also provides utility classes for accessing underlying system entities and services, such as ports, threads, and file systems.

The foundation class hierarchy is rooted at NSObject Class along with NSObject and NSCopying protocols
The foundation frameworks is logically grouped into Categories

1. Value Objects Encapsulates values of primitive data types including strings, integers , floats, dates etc
NSNumber instantiates numbers that contains integers, floats, doubles
NSDate, NSTimeZone, NSCalendar, NSDateComponents provides objects that represent times, dates, calendar and locales

2. Collections
NSArray, NSDictionary, NSSet along with the mutable variants

3. Operation System Services

File System and URL
NSFileManager. NSFileHandle, NSURL etc

NSThread, NSOperation, NSOperationQueue

Interprocess Communication –

Networking –
NSNetService, NSNetServiceBrowser

4. Notifications

5. Archiving and Serialization

6. XML Processing – NSXML

7. Predicates and Expressions – NSPredicate, NSCompoundPredicate, NSComparisonPredicate

8. Spotlight Queries NSMetadataItem. NSMetadataQuery

11. Details about the AppKit Framework

  • AppKit framework is needed for implementing graphical, event -driven user interface in OSX like window, buttons, panels, menus, scroller, text field, table views etc.
  • The root of the AppKit framework is the NSResponder class
  • AppKit is divided primarily into these areas
    • User Interface Classes
      • Global Application Object – NSApplication
      • Windows and Views – NSWindow, NSView
      • Controller Classes – NSObjectController, NSArrayController, NSDictionaryController, NSTreeController
      • Panels (Dialogs) – NSPanel
      • Menus and Cursors – NSMenu, NSMenuItem, NSCursor
      • Grouping and ScrollViews – NSBox, NSScrollView, NSSplitView etc
      • Tables and Outline Views
    • Text and Fonts – NSFont, NSFontManager
    • Graphics and Colors – NSImage, NSColor, NSColorPanel. NSColorWell, NSGraphicsContext, NSBezierPath etc
    • Printing and Faxing (NSPrinter, NSPrintPanel, NSPageLayout, NSPrintInfo)
    • Document and File System Support NSFileWrapper, NSFileManager
    • Sharing Data with other applications – NSPasteBoard,
    • Dragging
    • Spell Check – NSSpellServer


12. What is Core Data?

  • Core Data is a cocoa framework that provides infrastructure for managing object graphs, persistent storage
  • Core Data saves model objects to a persistent store and fetches them
  • Central concept of Core Data is managed object. A managed object is a model object that is an instance of NSManagedObject
  • Managed Context – All managed objects must be registered in the managed object context. the context allows an application to add objects to the graph and remove them from it.

13. Difference between Dynamic Typing, Dynamic Binding and Dynamic Loading in Objective C.

  • Dynamic typing—determining the class of an object at runtime
  • Dynamic binding—determining the method to invoke at runtime
  • Dynamic loading—adding new modules to a program at runtime

14. What are Categories?

Categories give us a way to add methods to a class without having to make a subclass. The methods in the category become part of the class type (within the scope of your program) and are inherited by all the class’s subclasses. There is no difference at runtime between the original methods and the added methods. You can send a message to any instance of the class (or its subclasses) to invoke a method defined in the category.


#import <Foundation/Foundation.h>
@interface NSTextField (MyAppExtensions)
-(NSString *)someFancyMethod;
#import "NSTextField_Category.h"
@implementation NSTextField (MyAppExtensions)
-(NSString *)someFancyMethod
//Write fancy method implementation code

Note: We cannot use category to add new instance variables to the class

15.    What is a protocol, how do the code confirm to the protocol?

a.    Objective-C defines a way to declare a set of behaviors without specifying an implementation.

b.    Methods are not associated to any class,

ex-mousedown, mousedragged.

c.     Any class can adopt the protocols and implement its method.

d.    Protocol is independent of class hierarchy.

e.    Conforming to a Protocol:-> A class is said to conform to a formal protocol if it adopts the protocols or inherits from a class that adopts it.

16.    What is the use of protocols?

a.    Declare methods that others are expected to implement.

b.    Declare interfaces while concealing the class.

c.    Non Hierarchical similarities: two dissimilar classes have some methods in common, now this methods can be grouped under Protocols.

17. Describe Protocols with an example?

Protocols are used for defining a set of behavior that is expected of an object. An example is a TableView can have datasource and the datasource can be the view controller or a standalone file that implements the mandatory datasource methods to be come the source of data to be displayed in the table view

Protocols define messaging contracts, A protocol is used to declare methods and properties that are independent of any specific class

Protocol Syntax

@protocol MyNewProtocol

// Here goes the list of method names and associated properties


Objective C uses angle brackets to indicate conformance to protocol. Conformance to multiple protocols is done through comma separated value

Sample Code

  @interface MyClass :NSObject <NSTableViewDelegate, NSTableViewDataSource, NSWindowDelegate,NSPopoverDelegate>
  //Instance Variables specific to MyClass
  //Method of MyClass
In a different approach conformance to protocol can be done as the following
  @interface MyClass: NSObject
  @property (weak) id <NSTableViewDataSource> dataSource;

In the above code a weak property is declared for a generic object pointer that conforms to NSTableViewDataSource protocol

Protocols Can Have Optional Methods

By default, all methods declared in a protocol are required methods. This means that any class that conforms to the protocol must implement those methods.
It’s also possible to specify optional methods in a protocol. These are methods that a class can implement only if it needs to.

Protocol methods can be marked as optional using the @optional directive, like this:

@protocol MyProtocol
  @required //If not stated explicitly, every method in a protocol is required
  – (NSNumber *)methodOne;
  – (NSNumber *)methodTwo;
  – (NSNumber *)methodThree; //methodThree is marked as Optional

If a method is marked as optional, we must check whether the object implements an optional method before trying to call it.

if([self.objectInstance respondsToSelector:@selector(methodThree:)]

Protocols can inherit from another protocol


18. What are Interfaces?

Interfaces as in Java are similar to Protocols in Objective C.

The interface in Objective C, Cocoa is the place where we define the member variables, state the superclass, conform to protocol, define method to be implemented, Declare property type.

A common interface declaration can be as follows

@interface MyNewClass : NSViewController <NSTableViewDataSource>
  IBOutlet     NSTableView *myTableView;
  IBOutlet NSTextField *nameTextField;
  NSMutableArray *dataArray;
  @property (nonatomic, retain) NSMutableArray *dataArray;

19. What is Declared Properties in Objective C?

Objects have properties and properties have attributes and relationships with other objects.

In traditional objective C, properties were defined by declaring instance variables and by implementing accessor methods (getter & setter method) to enforce encapsulation.

With declared properties, we have to no longer implement accessor methods. Direct access to the property value is also possible by dot notation.

There are 3 aspects to a properties

  • Declaration
  • Implementation
  • Access

We can declare properties in class, category, protocols in the declarative section.

@property(attributes…)type propertyName

Attributes are one or more optional attributes (comma separated)

Attributes are as follows

  1. readonly – property can only be read from, not written into. compiler does not synthesize a setter accessor
  2. readwrite – read from and written to. Default if readonly is not stated.
  3. assign – default, simple assignment should be used in the implementation of the setter
  4. retain – retain should be sent to the property upon assignment
  5. copy – copy should be sent to the property upon assignment
  6. nonatomic – By default all synthesized accessor methods are atomic so that a getter method is guaranteed to return a valid value even when multiple values are executing simultaneously

In the @implementation blocks of a class definition, you can use the @dynamic and @synthesize directives to control whether the compiler synthesizes accessor methods for particular properties.

  • @dynamic propertyName [, propertyName2…];
  • @synthesize propertyName [, propertyName2…];

The @dynamic directive tells the compiler that you are implementing accessor methods for the property, either directly or dynamically. The@synthesize directive, on the other hand, tells the compiler to synthesize the getter and setter methods if they do not appear in the @implementation block.

20. What is Fast Enumeration?

Used for efficient enumeration of collections
Provides mutation guard to prevent modification of the collection object during enumeration. An exception is thrown if a mutation is attempted.
Foundation declares the NSFastEnumeration protocol and the foundation classes such as NSArray, NSSet and NSDictionary adopt this protocol

On executing the below code
 NSArray *array = [NSArray arrayWithObjects:@"One",@"two",@"three", nil];
  for (NSString *str in array)
  NSLog(@"The String in array is -- %@",str);
NSString *myStr;
  NSSet *set = [NSSet setWithObjects:@"1",@"2",@"3", nil];
  for ( myStr in set)
  NSLog(@"myStr in set is -- %@",myStr);
NSDictionary *dict = [NSDictionary dictionaryWithObjects:array forKeys:[set allObjects]];
  for (NSString *key in dict)
  NSLog(@"key is %@ and Object is %@",key,[dict objectForKey:key]);
 Following is the output
  The String in array is -- One
  The String in array is -- two
  The String in array is -- three
  myStr in set is -- 1
  myStr in set is -- 2
  myStr in set is -- 3
  key is 1 and Object is One
  key is 2 and Object is two
  key is 3 and Object is three

21. What are the root class in Cocoa?

  • The root class does not inherit from any other class all other classes inherit from the root class.
  • The root class primarily accesses and interacts with the objective C runtime
  • Cocoa has two root classes
    • NSObject
    • NSProxy (essential in the distributed object architecture)

22. How the Garbage Collector Works?

The work of garbage collection is done by an entity known as the garbage collector. To the garbage collector, objects in a program are either reachable or are not reachable. Periodically the collector scans through the objects and collects those that are reachable. Those objects that aren’t reachable—the garbage objects—are finalized (that is, their finalize method is invoked). Subsequently, the memory they had occupied is freed.

The critical notion behind the architecture of the Objective-C garbage collector is the set of factors that constitute a reachable object. These factors start with an initial root set of objects: global variables (including NSApp), stack variables, and objects with external references (that is, outlets).

23. What will happen if we double initialize an object?

NSString * str = [[NSString alloc] initWithString:@"Hello"];
str = [str initWithString:@" World"];

If we attempt to reinitialize, the framework class of the instantiated object raises an exception.

The second initialization in the code given above will result in a NSInvalidArgumentException being raised

24. What are the rules for implementing an Initializer Method

  • Always invoke the superclass (super) initializer first.
  • Check the object returned by the superclass. If it is nil, then initialization cannot proceed; return nil to the receiver.
  • When initializing instance variables that are references to objects, retain or copy the object as necessary (in memory-managed code).
  • After setting instance variables to valid initial values, return self unless:
    • It was necessary to return a substituted object, in which case release the freshly allocated object first (in memory-managed code).
    • A problem prevented initialization from succeeding, in which case return nil.
- (id)initWithAccountID:(NSString *)identifier {
 if ( self = [super init] ) {
  Account *ac = [accountDictionary objectForKey:identifier];
  if (ac) { // object with that ID already exists
  [self release];
  return [ac retain];
if (identifier) {
  accountID = [identifier copy]; // accountID is instance variable
  [accountDictionary setObject:self forKey:identifier];
  return self;
  [self release];
  return nil;
  return nil;

25 The difference between dealloc and finalize Methods

In Cocoa classes that use garbage collection, the finalize method is where the class disposes of any remaining resources and attachments of its instances before those instances are freed. In Cocoa classes that use traditional memory management, the comparable method for resource cleanup is the dealloc method. Although similar in purpose, there are significant differences in how these methods should be implemented.

In many respects, the dealloc method is the counterpart to a class’s init… method, especially its designated initializer. Instead of being invoked just after the allocation of an object,dealloc is invoked just prior to the object’s destruction. Instead of ensuring that the instance variables of an object are properly initialized, the dealloc method makes sure that object instance variables are released and that any dynamically allocated memory has been freed.

Similar to the dealloc method, the finalize method is the place to close resources used by an object in a garbage-collected environment prior to that object being freed and its memory reclaimed. As in dealloc, the final line of a finalize implementation should invoke the superclass implementation of the method. However, unlike dealloc, a finalize implementation does not have to release instance variables because the garbage collector destroys these objects at the proper time.

But there is a more significant difference between the dealloc and finalize methods. Whereas implementing a dealloc method is usually required, you should not implement a finalize method if possible. And, if you must implement finalize, you should reference as few other objects as possible. The primary reason for this admonition is that the order in which garbage-collected objects are sent finalize messages is indeterminate, even if there are references between them. Thus the consequences are indeterminate, and potentially negative, if messages pass between objects being finalized. Your code cannot depend on the side effects arising from the order of deallocation, as it can in dealloc. Generally, you should try to design your code so that such actions as freeing memory allocated with malloc, closing file descriptors, and unregistering observers happen before finalize is invoked.

26. What are Class Factory Methods?

Class factory methods are implemented by a class as a convenience for clients.

They combine allocation and initialization in one step and return the created object.

However, the client receiving this object does not own the object and thus (per the object-ownership policy) is not responsible for releasing it.

These methods are of the form + (type)className… (where classNameexcludes any prefix).

Some Examples of Class factory methods in NSDate Class are

+ (id)dateWithTimeIntervalSinceNow:(NSTimeInterval)secs;

+ (id)dateWithTimeIntervalSinceReferenceDate:(NSTimeInterval)secs;

+ (id)dateWithTimeIntervalSince1970:(NSTimeInterval)secs;

27. What is Introspection?

Introspection refers to the capability of objects to divulge details about themselves as objects at runtime

Details such as whether the object conforms to a protocol, whether it responds to certain message.

Introspection helps avoid message-dispatch error, erroneous assumptions of object equality

Introspection works with class and superclass instance method which returns the the Class objects representing the class and superclass for the receiver.

To check the objects affiliation, we can sent it a isKindOfClass: or isMemberOfClass: message. 

The isKindOfClass returns whether the receiver is an instance of a given class or an instance of any other class

The isMemberOfClass: tells if the receiver is an instance of the specified class

28. How to do Object Comparison?

hash and isEqual: methods are runtime tools for identifying and comparing objects.

hash is implemented to return an integer that can be used as a table address in a hash table structure. If two objects are equal they will have the same hash value.

isEqual: checks for pointer equality.

29. Mutable vs immutable?

Objects by default are mutable. Objects allow to change their encapsulated date through setter accessor methods

For immutable objects the encapsulated values cannot be changed once an object is created.

example of mutable classes in Foundation framework



30. What is Toll Free Bridging?

There are a number of data types in the Core Foundation framework and the Foundation framework that can be used interchangeably. This capability, called toll-free bridging, means that you can use the same data type as the parameter to a Core Foundation function call or as the receiver of an Objective-C message.

For example, NSLocale is interchangeable with its Core Foundation counterpart, CFLocale


NSLocale *gbNSLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
CFLocaleRef gbCFLocale = (__bridge CFLocaleRef) gbNSLocale;
CFStringRef cfIdentifier = CFLocaleGetIdentifier (gbCFLocale);
NSLog(@"cfIdentifier: %@", (__bridge NSString *)cfIdentifier);
CFRelease((__bridge CFLocaleRef) gbNSLocale); 
CFLocaleRef myCFLocale = CFLocaleCopyCurrent();
NSLocale * myNSLocale = (__bridge NSLocale *) myCFLocale;
NSString *nsIdentifier = [myNSLocale localeIdentifier];
NSLog(@"cfIdentifier: %@", nsIdentifier);
CFShow((CFStringRef) [@"nsIdentifier: " stringByAppendingString:nsIdentifier]);


2013-11-09 23:26:15.877 GenericFunctionalities[15093:303] cfIdentifier: en_GB
2013-11-09 23:26:15.878 GenericFunctionalities[15093:303] cfIdentifier: en_US
nsIdentifier: en_US

31. What is Objective C memory management?

Allocate memory during program’s run time, use it and then free it when done using it.

Use as little memory as possible.

Manage the lifecycle of objects and then free them when they are no longer needed

There are 2 methods of Memory Management in Objective C

  • MRR – Manual Retain Release (We explicitly manage memory by keeping track of objects we own). Using the reference counting model.
  • ARC –Automatic Reference Counting. The system inserts appropriate memory management method calls for us at compile time

There are two major problems with Memory Management

  • Over-freeing (Leads to crashes)
  • Not Freeing (Leads to memory leaks, leading to increase in memory footprint of the application

32. What are the rules of memory management

Memory Management is based on ownership model. An object can have one or more owners, As long as an object has an owner it continues to exist. If the object has no owners, the runtime system destroys it

The basic rules of memory management are

  • You own the object if you have created it using alloc, new, copy, mutableCopy
  • You own the object if you have taken ownership of the object using retain
  • When the object is no longer needed, we must relinquish the object using release or autorelease
  • We must not relinquish objects that we do not own


33. When should we use autorelease?

Use autorelease when you need to send a deferred release message—typically when returning an object from a method. For example, you could implement the fullName method like this:

Sample 1:

-(NSString *)employeeName{
NSString *string = [[[NSString alloc] initWithFormat:@"%@ %@",self.firstName, self.lastName] autorelease];
return string;

Sample 2:

-(NSString *)employeeName{
NSString *string = [[NSString alloc] initWithFormat:@"%@ %@",self.firstName, self.lastName];
return [string autorelease];

In sample 1 and 2, We allow the caller of the method to use the returned string before it is deallocated

Sample 3: (No Memory Management Required)

-(NSString *)employeeName{
NSString *string = [NSString stringWithFormat:@"%@ %@",self.firstName, self.lastName];
return string;

Note: In the above sample code we have used the convenience constructor “stringWithFormat” and thus we do not need to do memory management using release or autorelease as we do not own the object returned from  “stringWithFormat”

34. Using Dealloc to relinquish ownership of Objects

The role of dealloc method is to free the objects own memory and to dispose of any resource it holds, including the ownership of any object instance variable


@interface Employee:NSObject
@property(retain) NSString *employeeName;
@property(retain) NSString *emailId;

@implementation Employee
[_employeeName release];
[_emailId release];
[super dealloc];//Super Dealloc call is required as the last line of the dealloc method

We should not invoke the dealloc method of another object

Note: Dealloc method should not be used to manage scare resource

35. Using Accessor Methods

@interface Employee:NSObject
@property(nonatomic, retain) NSString *employeeName;
@property(nonatomic, retain) NSString *emailId;

Each property declares two accessor methods. When we synthesize a property using the @synthesize directive the getter and setter method is automatically created.

If we have used the @dynamic directive for the property then we have to write our accessor methods

-(NSString *)employeeName{
return _employeeName;
-(void)setEmployeeName:(NSString *)newName
[newName retain];
[_employeeName release];
_employeeName = newName;

Setting Property Values

Sample 1:

[self setEmployeeName:@”John Doe”];

Sample 2:

NSString *str = [[NSString alloc] initWithFormat:@”%@%@”,self.firstName, self.lastName];

[self setEmployeeName:str];

[str release];

 Note: The accessor method should not be used in the initializer and the dealloc methods

36. What is Retain Cycles and how to avoid retain cycles

Retaining an object creates a strong reference. Objects cannot be released until all its strong references are released. A problem (retain cycles) will occur when two objects are having strong references to each other and thus both the objects will never get released.

The solution to the retain cycle problem is to use weak references. A weak reference is a non owning relationship where the source object does not retain the object to which it has a reference

e.g Notification Center stores a weak reference to the object and sends messages to it when appropriate notifications are posted. When an object is deallocated, it must be unregistered from the notification center to prevent the notification center from posting it a notification after it has been released.

37. Who owns the objects in a collection

Collections own the object that they contain and take ownership of it. The collection will relinquish ownership when objects are removed from the collection

38. What is Retain Count

The ownership policy is implemented through reference counting—typically called “retain count” after the retain method. Each object has a retain count.

  • When you create an object, it has a retain count of 1.
  • When you send an object a retain message, its retain count is incremented by 1.
  • When you send an object a release message, its retain count is decremented by 1.When you send an object a autorelease message, its retain count is decremented by 1 at the end of the current autorelease pool block.
  • If an object’s retain count is reduced to zero, it is deallocated.

39.    What are auto release pools? 

  • An autorelease pool is an instance of NSAutoreleasePool that “contains” other objects that have received an autorelease message.
  • When the autorelease pool is deallocated it sends a release message to each of those objects. An object can be put into an autorelease pool several times, and receives a release message for each time it was put into the pool.
  • Thus, sending autorelease instead of release to an object extends the lifetime of that object at least until the pool itself is released (the object may survive longer if it is retained in the interim).
  • Cocoa always expects there to be an autorelease pool available.If a pool is not available, autoreleased objects do not get released and you leak memory.
  • If you send an autorelease message when a pool is not available, Cocoa logs a suitable error message.

40.    What will happen if we send an autorelease or retain to an auto release pool?

  • We create an NSAutoreleasePool object with the usual alloc and init messages, and dispose of it with release (an exception is raised if we send autorelease or retain to an autorelease pool).
  • An autorelease pool should always be released in the same context (invocation of a method or function, or body of a loop) in which it was created.
  • Autorelease pools are arranged in a stack, although they are commonly referred to as being “nested.” When we create a new autorelease pool, it is added to the top of the stack. When pools are deallocated, they are removed from the stack. When an object is sent an autorelease message, it is added to the current topmost pool for the current thread.

41.    When should we create and destroy auto release pools

  • Writing a program that is not based on the Application Kit when there is no built-in support for autorelease pools.
  • If we spawn a secondary thread, we must create your own autorelease pool as soon as the thread begins executing  e.g.:If we write a loop that creates many temporary objects, you may create an autorelease pool inside  the loop to dispose of those objects before the next iteration.
  • Each thread in a Cocoa application maintains its own stack of NSAutoreleasePool objects. When a thread terminates, it automatically releases all of the autorelease pools associated with itself.
  • Autorelease pools are automatically created and destroyed in the main thread of applications based on the Application Kit,
    • So your code normally does not have to deal with them there. If you are making Cocoa calls outside of the Application Kit’s main thread, however, you need to create your own autorelease pool.This is the case if you are a Foundation-only application or if you detach a thread. If your  application or thread is long-lived and potentially generates a lot of autoreleased objects,you should periodically destroy and create autorelease pools(like the Application Kit does on the main thread); otherwise,autoreleased objects  accumulate and your memory footprint grows.
  • If your detached thread does not make Cocoa calls,you do not need to create an autorelease pool.

42.    When are auto release pools created?

a.    The Application Kit automatically creates a pool at the beginning of the event cycle (such as a mouse down event) and releases it at the end.

43. What is ARC-Automatic Reference Counting?

ARC is a compiler feature that provides automatic memory management for Objective C Objects, so that developers can focus primarily on building application functionality and not worry about retain and releases.

ARC follows the same principles of Manual Memory Management.

Manual memory management although straightforward involved lots of details and rules, Rules such as, when to use autorelease, when to retain, when to release, when to use convenience constructor (e.g NSString stringWithFormat) vs [[NSString alloc] initWithString]. With manual memory management, developers were expected to know how to use memory management tools such as Instruments, Static Analyzer, Object Alloc etc to identify leaks, zombies etc.

ARC evaluates the object lifetime requirement and accordingly inserts appropriate memory management calls at compile time. The compiler also creates the dealloc method on behalf of the developer.

44. What are the rules or ARC?

ARC enforces rules, which if not adhered to will give compile-time error.

  • Cannot invoke dealloc explicitly
  • Cannot implement retain, release, retainCount or autorelease
  • Dealloc methods can be implemented for managing resources other than instance variables.
  • If Dealloc is used, [super dealloc] call is not required and using [super dealloc] will lead to compile error.
  • CFRetain, CFRelease can be used with Core Foundation Type objects
  • NSAutoreleasePool cannot be used, if required @autoreleasepool block can be used.
//Huge amount of temporary objects are created here
  • Memory zones cannot be used.
  • “new” cannot be used for beginning a property declaration.

45. Can a project have both ARC and Non-ARC code?

Projects can have both ARC and Non-ARC code, when a project is created to use ARC, the –fobj-arc compiler flag is set.
The ARC can be disabled for specific classes using the –fno-objc-arc.
Xcode→Project→Build Phase→Compile Sources→ Double Click on class and set the –fno-objc-arc

46. What are the property attributes in ARC?

Strong, Weak, Unsafe_Unretained & autoreleasing

 @property (strong) DdClass *ddObject;
is same as @property(retain) DsClass *ddObject;

Strong is default. Objects remain alive as long as there is a strong pointer to it.

@property(weak) DdClass *ddObject; is same as @property(assign) DdClass *ddObject;

except that in case of weak, the property value is set to nil instead of remaining as a dangling pointer as in the case of assign. “weak” specifies a reference that does not keep the referenced object alive. A weak reference is set to nil when there are no strong references to the object.

Unsafe_unretained does not keep the referenced object alive and at the same time does not set it to nil, So when the object being referenced is deallocated, the pointer is left dangling.

Autoreleasing – used to denote arguments that are passed by reference (id *) and are autoreleased on return.

With ARC the instance variables are implicitly initialized to nil.

47.    Examples of predefined exceptions

  1. NSGenericException
  2. NSRangeException
  3. NSInvalidArgumentException
  4. NSMallocException

48.    How do we create custom exceptions and what method do we use to propagate them

NSException myException = [NSException


reason:@”File Not Found on System”


[myException raise];

49.    Try Catch Finally- What is the equivalent in Objective C




50. What is the basic difference between the Foundation and the AppKit Framework?

1)Foundation (Foundation.Framework)

–Root Object

–Classes representing basic data types such as strings and byte arrays.

–Collection of classes for storing other Objects

–Classes representing system information such as dates.

–Classes representing Communication Ports

2)Application Kit (AppKit.Framework)

—Graphical, event-driven user interface- Windows, panels, buttons, menus, scrollers, text fields etc.

—communication with hardware devices and screen buffers

—Event handling, application and document management

—Integrate and manage fonts, colors, printing etc

51.   Name a few collection objects in Cocoa/ Objective C?

 Arrays: Ordered Collections of Objects

Counted Sets: Unordered Collection of Indistinct Objects

Dictionaries: Collections of Keys and Values

Enumerators: Traversing a Collection’s Elements

Sets: Unordered Collections of Objects

52.  What are delegate methods ?

Delegates provide us with a way to notify an object about another object’s state, but an object can have only one delegate

Notifications overcome this drawback

Use notifications when many objects need to know about another objects state.

53. When do we use notifications?

Notification Center (NSNotificationCenter ):

Objects that need to know about an event, register themselves with the notification center. A notification posted at notification center is broadcasted to all the registered objects.

Notification Queues (NSNotificationQueue):

This act as buffers for notification centers. A notification queue maintains notifications generally in a First In First Out (FIFO) order

54. How does the object posting a notification associate more information in the notification message?

userInfo – object posting the notification can put some useful information as a dictionary here.

55. What is the ideal place to registering a class with the notification center



Init Method

56. Can we do operator overloading in Objective C


57. Difference between self.object = foo; and object = foo;

The difference between these two calls is that a call to self.object will make use of the accessors generated by the @synthesize directive.

A call to the object directly will bypass these accessor methods and directly modify the instance variable in question.

It’s important to realise that the dot syntax is a short hand for calling the accessor

58. Can we have multiple inheritance in Objective C


59. Does the sorting on the table views actually sort the data down below or only the representation  is sorted.

The sorting of table view only sorts the representation. rather than selecting an object in an array based on the selected row index, we should use use selected object of the array controller.

60. If we wish to call a particular method after an interval of 5 seconds each how do we do that.

NSTimer *tmr = [NSTimer






61. How do we stop a NSTimer?

Calling the Invalidate method of the timer instance.

62. Should we initialize member variables in the init function?

Don’t initialize variables to 0 or nil in the init method; it’s redundant.

63.   How can we execute a mathematical function from a string  in Objective C

One of the option is Using @”/usr/bin/bc”

64. How can we call a method just by passing the method name as a string

aSelector =  NSSelectorFromString(newVar);
aSignature = [self methodSignatureForSelector:aSelector];
NSInvocation *anInvocation = [NSInvocation invocationWithMethodSignature:aSignature];
[anInvocation setSelector:aSelector];
[anInvocation setTarget:self];
[anInvocation invoke];

65. What is Singleton Class?

By restricting the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.

The concept is sometimes generalized to systems that operate more efficiently when only one object exists,

66. What is the difference between nil, Nil, NULL & NSNull?

C represents nothing as 0 for primitive values and NULL for pointer

“nil” is an object pointer to nothing

“Nil” – Nil is a class pointer to nothing

NULL – in C , nothing is represented as 0 for primitive values and NULL for pointers.
NSNull – NSNull is a foundation class that has class method +null which returns a singleton NSNull Object. NSNull is used as a container for nil or NULL Values so that it can be used in a collection (array or dictionary)

67. Some of the important Classes in Cocoa are as follows

  • NSNumber – Can instantiate object that contains integers, floats or doubles
  • NSData – For storing streams of bytes, Writing data objects to the file system and reading from them
  • NSDate- Displaying dates, times in many formats. Time adjustments based on time zones
  • NSString – Different representation of character strings such as UTF-8 etc
  • NSAttributedString – Supports strings with attributes such as font etc
  • NSArray – Ordered collection of objects, uses zero based indexing
  • NSDictionary – Managing key value pairs, Dictionaries are unordered and must contain unique keys
  • NSSet – Similar to NSArray but unsorted. Contains distinct objects
  • NSFileManager – Used for file operations
  • NSThread – Used for creating multithreaded programs
  • NSOperation & NSOperationQueue – To perform multiple operations (concurrent & Non-Concurrent) in priority and dependence order
  • NSXMLParser – To process XML Data
  • NSXML – Used to represent a XML document as a hierarchial tree

68. What is a Framework

Framework encapsulates both code and resources. A framework might contain the compiled code only or both header files, compiled code, resources such as images, documentation,String files, XIBs etc



Cocoa Fundamentals


2 comments on “Cocoa, Objective C Questions & Answers
  1. Hey! I stumbled your page web page on Twitter. I am posting
    here to know which theme you are using on your website, I would love to use the theme that you are using so I can put it on my page

    Thank you.

    • Debasis Das says:

      The theme is called “Responsive” and i have downloaded a child theme and done some customization primarily in the CSS

Leave a Reply

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


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Recent Posts

Hit Counter provided by technology news