Cocoa, Objective C Interview Questions – Part 2

Cocoa, Objective C Interview Questions – Part 2

Compiled By : Debasis Das (5-April-2015)

Part 2 in series on cocoa, objective c interview questionsThe questions will range between basic to intermediate to advanced concepts. Below is the second in the series.

This set of questions will primarily focus on Memory Management in Cocoa, Objective C

1. 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  In MRR 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

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

3. 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
      • readonly – property can only be read from, not written into. compiler does not synthesize a setter accessor
      • readwrite – read from and written to. Default if readonly is not stated.
      • assign – default, simple assignment should be used in the implementation of the setter
      • retain – retain should be sent to the property upon assignment
      • copy – copy should be sent to the property upon assignment
      • 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.

4. How to use 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

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

 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

 6. 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.

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

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

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

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

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

12. When are auto release pools created?

  • 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.

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

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

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

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

17. How does the Garbage Collector Work?

  • 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).


18. 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


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

20. What is 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.


Posted in Cocoa, Objective C Tagged with: , , , ,
One comment on “Cocoa, Objective C Interview Questions – Part 2
  1. Thanks for the great questions for checking the knowledge of memory management topics. Despite decline of MRR I think this deep knowledge is still useful in some cases.

1 Pings/Trackbacks for "Cocoa, Objective C Interview Questions – Part 2"
  1. […] Cocoa, Objective C Interview Questions – Part 2 […]

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