Featured post

Difference between protocol and delegates?

A protocol, declared with the ( @protocol syntax in Objective-C) is used to declare a set of methods that a class "adopts" (de...

Tuesday, 28 April 2015

Difference between protocol and delegates?

A protocol, declared with the (@protocol syntax in Objective-C) is used to declare a set of methods that a class "adopts" (declares that it will use this protocol) will implement. This means that you can specify in your code that, "you don't care which class is used as long as it implements a particular protocol". This can be done in Objective-C as follows:
id<MyProtocol> instanceOfClassThatImplementsMyProtocol;
If you state this in your code, then any class that "conforms" to the protocol MyProtocol can be used in the variable instanceOfClassThatImplementsMyProtocol. This means that the code that uses this variable knows that it can use whichever methods are defined in MyProtocol with this particular variable, regardless of what class it is. This is a great way of avoiding the inheritance design pattern, and avoids tight coupling.
Delegates are a use of the language feature of protocols. The delegation design pattern is a way of designing your code to use protocols where necessary. In the Cocoa frameworks, the delegate design pattern is used to specify an instance of a class which conforms to a particular protocol. This particular protocol specifies methods that the delegate class should implement to perform specific actions at given events. The class that uses the delegate knows that its delegate coforms to the protocol, so it knows that it can call the implemented methods at given times. This design pattern is a great way of decoupling the classes, because it makes it really easy to exchange one delegate instance for another - all the programmer has to do is ensure that the replacement instance or class conforms to the necessary protocol (i.e. it implements the methods specified in the protocol)!
Protocols and delegates are not restricted only to Objective-C and Mac/iOS development, but the Objective-C language and the Apple frameworks make heavy use of this awesome language feature and design pattern.


Introduction
Protocols can be helpful in a number of scenarios, a common usage is to define methods that are to be implemented by other classes. A familiar example is when using a tableview, your class implements the cellForRowAtIndexPath method which asks for cell content to insert into a table – the cellForRowAtIndexPath method is defined within the UITableViewDataSource protocol.




Protocols are like contracts, Your class must implement all methods that are @required, @optional are on the other hand not required.
Instead of Protocols why can't I make my classes do the same job? You can, but like I wrote above, its a contract. You know that class
implements the (Required) methods.
delegate is (should be) a weak reference to the class that implements the given protocol.
You are recommended to use the following attribute on your delegateproperty:
@property (assign) id<yourProtocol> delegate;
Notice that you don't retain your delegate. You you (weak) reference because you dont want to get into a retain circle (A retains B, and B retains A).
I hope my explanation helped a bit.

Parsing JSON vs parsing XML in iOS

Checkout this tutorial about parsing XMLs. I might sound opinionated, but if there's a choice go for JSON, although I have no clue what situation your project is in. I would certainly look at the entire architecture (trade-offs and choices) of the project before making a decision. From my experience, understanding JSON and relating it to NSDictionaries and NSArrays is much easier than understanding XMLs.

When JSON is preferred it is usually because it is significantly shorter. That saves transmission traffic and therefore time and battery power (not a bad thing, though?). Meaning: Even if parsing JSON would be slower (which I doubt), the gain during the tranfer over the air would certainly compensate any additional CPU time during parsing. 

SOAP vs. REST For Mobile Services

Definitions

Before diving into an analysis of SOAP vs. REST, it will be useful to define the terms used in the analysis.
  • SOAP:  “Simple Object Access Protocol”, is a protocol specification for exchanging structured information via XML in the implementation of Web Services in computer networks
  • REST:  “Representational State Transfer”, was defined by Roy Fielding.  It stresses that services can be interacted with via stateless representations of the targets of the service.  It leverages the transport layer that was implemented to support the world-wide web.
  • JSON: “Javascript Object Notation”, is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript programming language for representing simple data structures and associative arrays, called objects.
  • Mobile Facade:  is a service tier designed for mobile devices that puts in one place all the services required by a mobile application.  It may transform and consolidate data from other services.
  • WS-Security:  is an extension to SOAP that provides security to web services.
  • AJAX:  is a set of development methods and patterns that promote highly-interactive web applications by providing direct access to remote data and services directly from JavaScript running on a web page, thus bypassing the one-page-at-a-time model for accessing remote services.
  • Web 2.0:  is the concept of using AJAX, JSON and other tools to make for a richer user experience on the web.
  • PII: Personally identifiable information, such as social security numbers, account numbers, or HIPAA controlled information.
  • Data hiding: is a technique in data communication in which key data is never transmitted, but rather maintained by reference on ther server-side.  Used to protect PII.
  • Data protection: is a technique in data communication in which data is prevented from being viewed by unauthorized persons or processes.  Typically accomplished by encryption.
  • Non-repudiation: is the ability to ensure that a party to a communication cannot deny the authenticity of their signature on a message that they originated.  This is typically accomplished with digital certificates.
  • Authentication: is the process of determining the identity of a client using a service.
  • Authorization: is the process of determining what rights and access are availabile to a client that has been authenticated.

Analysis

SOAP

What SOAP Does Well

SOAP is a well-known technology that has been used effectively within a SOA framework for some time.  Many enterprises have established service tiers within their IT infrastructure to offer services to diverse applications, both inside and outside the firewall. SOAP was designed to take advantage of many different types of data transport layers including synchronous HTTP/HTTPS, asynchronous queues like MQSeries, and even over email.  This capability helps SOAP be a single solution for many heterogeneous interconnectivity problems. However, SOAP was designed before the explosion of mobile technology and mobile applications.

Problems

  • Change Control - Changing services that use SOAP often means a complicated code change on the client.  When this client is a web application server, this change is not necesarily problematic, but when the SOAP client is running on a mobile device, the problem of application update dissemination arises.
  • Complexity – Generating SOAP client code from WSDL’s and XSD’s can be quite complex, and in the mobile world, this complexity is magnified by the fact that many organizations must produce the same mobile application for several platforms (iOS, Android, etc).  Re-coding the complex SOAP interfaces several times can be time-consuming and error-prone.
  • Re-use – For many of the same reasons mentioned in this white paper, modern Web 2.0 applications that use AJAX have adopted RESTful services via JSON as the preferred way to have web pages directly access remote services.  Opportunities for re-use thus will be limited if mobile applications use SOAP instead of REST. As application's migrate toward HTML5 mobile web this reuse become increasingly important.

False Assumptions

  • SOAP is more secure – This assumption often comes up because there are specific security methods as part of the overall SOAP specification (WS-Security).  However one must realize that the reason WS-Security was created was largely because the SOAP specification was transport-independent and no assumptions could be made about the security availabile on the transport layer.  REST assumes that the transport will be HTTP (or HTTPS) and the security mechanisms that are built-in to the protocol will be available. 
  • The remote device is trustworthy – SOAP-based services have historically been consumed by code running on one application server that needs services from another entity.  Typically, both ends of the service communication are running on servers that are presumed to be secure.  The SOAP message-level or transport-level security is designed to secure the requests and responses while in transit.  In the case of mobile applications, assuming the device is trustworthy is a mistake.

REST

What REST Does Well

  • Simplicity - REST was designed to operate with thin clients, like a web browser, through all types of networking equipment, to a variety of service types (Java, .NET, PHP, Ruby, static HTTPd, etc.).  Because of this requirement for lightweight and flexible implementation, it is very simple and also very similar to the vast majority of web traffic on the Internet.
  • Infrastructure friendly - Network load balancers, real-user-monitoring gear, firewalls, proxies, are all, already, optimized for RESTful traffic because they are optimized for HTTP/S traffic.
  • Cacheable - Some categories of RESTful requests are well suited to caching, such as image requests, because the entire request is expressed in the URL. Network caching infrastructure, such as a CDN, can respond with a correct answer.
  • Scalable - When a REST services goes by the definition, REST requests are stateless which makes these types of requests very scalable.
  • Stateless or Stateful - Although The REST definition calls for stateless calls, the approach lends itself equally well to passing session data in a request header just like web browsers pass session information. Using a session context with REST calls allows the server to hold PII and just pass references or masked versions to an untrusted client.
  • Efficient - While SOAP services always return XML, REST services provide flexibility in regards to the type of data returned. A REST endpoint can just as easily return a payload of XML data as a PNG image. The de facto standard for data payloads from REST services is JSON.  This is because of the AJAX heritage of REST wherein JavaScript easily consumes JSON data. Initially Android and iOS did not contain JSON parsing frameworks as part of the OS, but in later revisions that functionality has been added. JSON payloads are usually smaller than their XML counterparts; if SOAP envelope overhead is included REST+JSON payloads are dramatically smaller.

Possible Problems

  • Security must be designed in - Security requires good design and discipline. Like any data protocol, REST security must be designed with the application data in mind. With mobile apps one must plan on the remote device being compromised.  One must carefully consider the data being transmitted to ensure that only the minimal amount of data is be sent to satisfy the application requirements. PII should not be sent to a mobile device unless absolutely necessary. Commands from the device should leverage information held in the server session and that data should be compared against the current context to verify semantic correctness.
  • No rigid standard – It is easy for developers to “miss the point”. We have seen many service implementations that claim to be RESTful services but are nothing more than a single servlet that inspects a posted payload for the operations to perform. This is a flawed approach and obviates many of the advantages of REST. Including command parameters in the request URL provides value to the systems monitoring and managing the request, such as caching proxies and load balancers. Using the full suite of HTTP request types (GET, POST, PUT, DELETE, etc.) will naturally provide a separation of concerns in the implementation.
  • Need to protect PII - Exposure of PII can happen just as easily using REST as using HTTP or SOAP.  One must be diligent to design the application and protocol so that PII is not transmitted to systems that are not trusted.  

Conclusion

Which web services approach to use is a fundamental decision that can affect the success of a mobile application.  For the reasons mention in this document, we believe that RESTful services, when implemented properly offer the best combination of:
  • Developer Productivity
  • Performance
  • Bandwidth Efficiency
  • Opportunity for Security
  • Robustness
... to contribute to the success and timeliness of delivery of a mobile application.

Sunday, 19 April 2015

Objective-C Automatic Reference Counting (ARC) Big explaination?

Objective-C declared @property attributes (nonatomic, copy, strong, weak)

Nonatomic
nonatomic is used for multi threading purposes. If we have set the nonatomic attribute at the time of declaration, then any other thread wanting access to that object can access it and give results in respect to multi-threading.
Copy
copy is required when the object is mutable. Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.
Assign
Assign is somewhat the opposite to copy. When calling the getter of an assign property, it returns a reference to the actual data. Typically you use this attribute when you have a property of primitive type (float, int, BOOL...)
Retain
retain is required when the attribute is a pointer to an object. The setter generated by @synthesize will retain (aka add a retain count to) the object. You will need to release the object when you are finished with it. By using retain it will increase the retain count and occupy memory in autorelease pool.
Strong
strong is a replacement for the retain attribute, as part of Objective-C Automated Reference Counting (ARC). In non-ARC code it's just a synonym for retain.
This is a good website to learn about strong and weak for iOS 5. http://www.raywenderlich.com/5677/beginning-arc-in-ios-5-part-1
Weak
weak is similar to strong except that it won't increase the reference count by 1. It does not become an owner of that object but just holds a reference to it. If the object's reference count drops to 0, even though you may still be pointing to it here, it will be deallocated from memory.
The above link contain both Good information regarding Weak and Strong.

Friday, 17 April 2015

What is the difference between Notifications, Delegates, and Protocols?


Protocols

 

Protocols are interfaces which define certain methods that objects respond to. The key thing about protocols is that they can be adopted by any class, guaranteeing that an object responds to those methods.
If you declare a protocol:
@protocol Photosynthesis
@required
- (void)makeFood:(id<Light>)lightSource;
@optional
+ (NSColor *)color; // usually green
@end
Then you can adopt it from other classes which are not necessarily directly related:
@interface Plant : Eukaryote <Photosynthesis>
// plant methods...
@end
@implementation Plant
// now we must implement -makeFood:, and we may implement +color
@end
or
@interface Cyanobacterium : Bacterium <Photosynthesis>
// cyanobacterium methods...
@end
@implementation Cyanobacterium
// now we must implement -makeFood:, and we may implement +color
@end
Now, elsewhere, we can use any of these classes interchangeably, if we only care about conformance to the protocol:
id<Photosynthesis> thing = getPhotoautotroph(); // can return any object, as long as it conforms to the Photosynthesis protocol
[thing makeFood:[[Planet currentPlanet] sun]]; // this is now legal

Delegates & Notifications

Documentation: Cocoa Design Patterns
These are two ways to pass messages between objects. The main difference:
  • with delegates, one designated object receives a message.
  • any number of objects can receive notifications when they are posted.
Delegates are usually implemented using protocols: a class will usually have something like
@property (weak) id<MyCustomDelegate> delegate;
which gives the delegate a certain set of methods to implement. You can use
myObject.delegate = /* some object conforming to MyCustomDelegate */;
and then the object can send relevant messages to its delegate. For a good common example, see the UITableViewDelegate protocol.
Notifications, on the other hand, are implemented using NSNotificationCenter. An object (or more than one object) simply adds itself as an observer for specific notifications, and then can receive them when they are posted by another object.
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(notificationHappened:)
                                             name:MyCustomNotificationName
                                           object:nil];
Then just implement
- (void)notificationHappened:(NSNotification *)notification {
    // do work here
}
And you can post notifications from anywhere using
[[NSNotificationCenter defaultCenter] postNotificationName:MyCustomNotificationName
                                                    object:self
                                                  userInfo:nil];

 

 

Wednesday, 15 April 2015

Swift 1.2 and Xcode 6.3 beta

 Swift 1.2 was released as part of Xcode 6.3 beta. This beta release includes a significantly enhanced Swift compiler, as well as new features in the Swift language itself. For the complete list of changes, read the release notes. This blog post will focus on the highlights.

Compiler improvements

The Swift 1.2 compiler was engineered to be more stable and to improve performance in every way. These changes also provide a better experience when working with Swift in Xcode. Some of the most visible improvements include:
  • Incremental builds — Source files that haven’t changed will no longer be re-compiled by default, which will significantly improve build times for most common cases. Larger structural changes to your code may still require multiple files to be rebuilt.
  • Faster executables — Debug builds produce binaries that run considerably faster, and new optimizations deliver even better Release build performance.
  • Better compiler diagnostics — Clearer error and warning messages, along with new Fix-its, make it easier to write proper Swift 1.2 code.
  • Stability improvements — The most common compiler crashes have been fixed. You should also see fewer SourceKit warnings within the Xcode editor.

New language features

In Swift 1.2, the language has been further refined to ensure safe, predictable behavior. We also continue to improve the interaction between Swift and Objective-C. Some of the more notable changes include:
  • as! for failable casts — Casts that can fail at runtime are now expressed with the new as!operator to make their potential for runtime failure clear to readers and maintainers of your code.
  • Nullability may now be expressed in Objective-C headers — New Objective-C extensions in Clang allow you to express the nullability of pointers and blocks in your Objective-C API. You can provide Objective-C frameworks that work great with Swift code, and improve your Swift experience when mixing and matching with Objective-C code in your own project.
  • Swift enums can now be exported to Objective-C using the @objc attribute — For example, the following Swift code:
@objc enum Bear: Int {
 case Black, Grizzly, Polar
}
imports into Objective-C as:
typedef NS_ENUM(NSInteger, Bear) {
 BearBlack, BearGrizzly, BearPolar
};
  • let constants are now more powerful and consistent — The new rule is that a let constant must be initialized before use (like a var), and that it may only be initialized, not reassigned or mutated after initialization.
This enables patterns like:
let x : SomeThing
if condition {
 x = foo()
} else {
 x = bar()
}
use(x)
This formerly required the use of a var even though there is no mutation taking place. Properties have been folded into this model to simplify their semantics in initializers as well.
  • More powerful optional unwrapping with if let — The if let construct can now unwrap multiple optionals at once, as well as include intervening boolean conditions. This lets you express conditional control flow without unnecessary nesting.
  • New native Set data structure — An unordered collection of unique elements that bridges withNSSet and provides value semantics like Array and Dictionary.

Conclusion


We appreciate all of the bugs you have filed, and expect that many of the most common issues have been fixed in this beta. Swift 1.2 is a major step forward for both the language and the tools. It does include some source-incompatible changes that require updates to your code, so Xcode 6.3 includes a migrator to help automate the process. To begin the migration, click the Edit menu, then choose Convert > To Swift 1.2...

Friday, 10 April 2015

Explain Nil - NULL – NSNULL

Answer:-

There are 3 ways to represent a null value in Objective-C.
Nil -> Absence of value with Objective-C object variables.
Null -> Absence of value with C- style pointers.
NSNULL ->A nil boxed as an object for storage in a collection.


Explain the difference between NSOperationQueue concurrent and non-concurrent?  

Answer:-

In the context of an NSOperation object, which runs in an NSOperationQueue, the terms concurrent and non-concurrent do not necessarily refer to the side-by-side execution of threads. Instead, a non-concurrent operation is one that executes using the environment that is provided for it while a concurrent operation is responsible for setting up its own execution environment.  

What is advantage of categories? What is difference between implementing a category and inheritance? 

Answer:-

You can add method to existing class even to that class whose source is not available to you. You can extend functionality of a class without subclassing. You can split implementation in multiple classes. While in Inheritance you subclass from parent class and extend its functionality.  

Difference between categories and extensions?

Answer:-

Class extensions are similar to categories. The main difference is that with an extension, the compiler will expect you to implement the methods within your main @implementation, whereas with a category you have a separate @implementation block. So you should pretty much only use an extension at the top of your main .m file (the only place you should care about ivars, incidentally)  

Important answer on memeory allocation

What happens when you add autorelease two times?
Answer:

Adding autorelease two times will release the object twice,your app will crash, because you'll be releasing a deallocated object.
 
What is the use of Controller?
Answer:-


In iOS, the controller is generally a subclass of UIViewController that manages a view, it is also responsible for responding to delegation      messages and target-action messages.  


Example:
You have a UITableViewController which is a subclass of                   
  UIViewController hat manages a UITableView  

What is ARC?
Answer:-

Automatic Reference Counting, or ARC was introduced in  iOS 5,is a feature of the new LLVM 3.0 compiler and it completely does away with the manual memory management.you no longer call retain, release and autorelease.With Automatic Reference Counting enabled, the compiler will automatically insert retain, release and autorelease in the correct places in your program ARC is not a runtime feature (except for one small part, the weak pointer system), nor is it *garbage collection* that you may know from other languages.All that ARC does is insert retains and releases into your code when it compiles it.

OR

ARC is a compiler-level feature that simplifies the process of managing the lifetimes of Objective-C objects. Instead of you having to remember when to retain or release an object, ARC evaluates the lifetime requirements of your objects and automatically inserts the appropriate method calls at compile time.  

What is retain ?
Answer:-

it is retained, old value is released and it is assigned -retain specifies the new value should be sent -retain on assignment and the old value sent -release -retain is the same as strong. -apple says if you write retain it will auto converted/work like strong only. -methods like "alloc" include an implicit "retain"  


What is atomic?
Answer:-

-Atomic means only one thread access the variable(static type). -Atomic is thread safe. -but it is slow in performance -atomic is default behaviour -Atomic accessors in a non garbage collected environment (i.e. when using retain/release/autorelease) will use a lock to ensure that another thread doesn't interfere with the correct setting/getting of the value. -it is not actually a keyword.

Example :
@property (retain) NSString *name;
@synthesize name;  

Difference between shallow copy and deep copy?
Answer:-

Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.
Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.
OR
Shallow copy is also known as address copy. In this process you only copy address not actual data while in deep copy you copy data.

Suppose there are two objects A and B. A is pointing to a different array while B is pointing to different array. Now what I will do is following to do shallow copy.
Char *A = {‘a’,’b’,’c’};
Char *B = {‘x’,’y’,’z’};
B = A;
Now B is pointing is at same location where A pointer is pointing.Both A and B in this case sharing same data. if change is made both will get altered value of data.Advantage is that coping process is very fast and is independent of size of array.

while in deep copy data is also copied. This process is slow but Both A and B have their own copies and changes made to any copy, other will copy will not be affected.  


What is purpose of delegates?
Answer:- 

A delegate allows one object to send messages to another object when an event happens. For example, if you're downloading data from a web site asynchronously using the NSURLConnection class. NSURLConnection has three comment delegates:

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
-(void)connection:(NSURLConnection *)connection didReceiveResponse
- (NSURLResponse *)response  

What is Blocks in Objective-C ?

In Objective-C class defines an object that combines data with related     behaviour. Sometimes, it makes sense just to represent a single task or   unit of behaviour, rather than a collection of methods.

Blocks are a language-level feature added to C, Objective-C and C++         which allow you to create distinct segments of code that can be passed   around to methods or functions as if they were values. 

Blocks are Objective-C objects which means they can be added to           collections like NSArray or NSDictionary. They also have the ability to     capture values from the enclosing scope, making them similar to             closures or lambdas in other programming languages

Block declaration syntax:

returntype (^blockName)(argumentType);
Simple block implementation
returntype (^blockName)(argumentType)= ^{
};

Here is a simple example:


void (^simpleBlock)(void) = ^{
    NSLog(@"This is a block");
};

How to invoke:

simpleBlock();
 

What is the difference Between APPKit and UIKit?

AppKit
AppKit is included in the OS X SDK only.It provides all the classes and controls you need for creating Mac applications.Most of these classes share a common naming prefix starts with NS and classes you will be working with include - 

UIKit

UiKit is the framework that iOS uses to provide its UI and its classes         start with a UI prefix. For example, both frameworks have a class to         represent color include UIColor,while other concepts are pretty       unique to UIKit, such as its use of predefined controllers such as               UINavigationController and UITabBarController - 

What is the difference b/w loadview and viewdidload ? 

oadView

loadView is called by the view controller to load the view. It is the active action of creating and instantiating the UIView object. This is where the   view controller decides how the view should look based on what it         knows from the storyboard.

viewDidLoad

viewDidLoad is called after loadView has completed all its tasks and the UIView is ready for display. It is where you initialize any properties of     the view or the view controller object and finalize them before                 viewWillAppear is called.

If you are using storyboard, you would almost never use loadView. Even if you do, most of the initialization of different properties of the view        should be done in viewDidLoad, as stated in the Apple documentation.  - See more at: http://huntmyideas.weebly.com/blog/ios-interview-questions-and-answers-part-6#sthash.3NexgFV7.dpuf

NSURLConnection class, types and how to use.

 

There are two ways of using the NSURLConnection class. One is asynchronous, and the other is synchronous. An asynchronous connection will create a new thread and does its downloading process on the new thread. A synchronous connection will block the calling thread while downloading content and doing its communication. 
Many developers think that a synchronous connection blocks the main thread, but that is incorrect. A synchronous connection will always block the thread from which it is fired. If you fire a synchronous connection from the main thread, yes, the main thread will be blocked. But if you fire a synchronous connection from a thread other than the main thread, it will be like an asynchronous connection in that it won’t block your main thread. In fact, the only difference between a synchronous and an asynchronous con‐ nection is that the runtime will create a thread for the asynchronous connection, while it won’t do the same for a synchronous connection. 
In order to create an asynchronous connection, we need to do the following: 

  1.    Have our URL in an instance of NSString. 
  2.    Convert our string to an instance of NSURL. 
  3.   Place our URL in a URL Request of type NSURLRequest, or in the case of mutable URLs, in an instance of NSMutableURLRequest. 
  4.    Create an instance of NSURLConnection and pass the URL request to it. 

NSMutableURLRequest and NSURLConnection can't work in GCD dispatch_async?

It's not that you're using a mutable connection in one place and not the other, it's that you're calling the synchronous request method which runs immediately on the current thread versus an asynchronous method which needs a run loop to operate. From the documentation for -[NSURLConnection start]:
If you don’t schedule the connection in a run loop or an operation queue before calling this method, the connection is scheduled in the current run loop in the default mode.
Calling the asynchronous method from a block on a background thread is redundant. You should either call the async method on the main thread (it returns immediately and schedules its work in the background) or call the synchronous method in the async dispatched block. Doing it the second way, you don't have to deal with all the delegate callbacks, but you give up some control over the load operation.

Thursday, 9 April 2015

what is ARC ?deep explaination

ARC Overview

Instead of you having to remember when to use retainrelease, and autorelease, ARC evaluates the lifetime requirements of your objects and automatically inserts appropriate memory management calls for you at compile time. The compiler also generates appropriate dealloc methods for you. In general, if you’re only using ARC the traditional Cocoa naming conventions are important only if you need to interoperate with code that uses manual reference counting.
A complete and correct implementation of a Person class might look like this:
@interface Person : NSObject
@property NSString *firstName;
@property NSString *lastName;
@property NSNumber *yearOfBirth;
@property Person *spouse;
@end
 
@implementation Person
@end
(Object properties are strong by default; the strong attribute is described in ARC Introduces New Lifetime Qualifiers.)
Using ARC, you could implement a contrived method like this:
- (void)contrived {
    Person *aPerson = [[Person alloc] init];
    [aPerson setFirstName:@"William"];
    [aPerson setLastName:@"Dudney"];
    [aPerson setYearOfBirth:[[NSNumber alloc] initWithInteger:2011]];
    NSLog(@"aPerson: %@", aPerson);
}
ARC takes care of memory management so that neither the Person nor the NSNumber objects are leaked.
You could also safely implement a takeLastNameFrom: method of Person like this:
- (void)takeLastNameFrom:(Person *)person {
    NSString *oldLastname = [self lastName];
    [self setLastName:[person lastName]];
    NSLog(@"Lastname changed from %@ to %@", oldLastname, [self lastName]);
}
ARC ensures that oldLastName is not deallocated before the NSLog statement.

ARC Enforces New Rules

To work, ARC imposes some new rules that are not present when using other compiler modes. The rules are intended to provide a fully reliable memory management model; in some cases, they simply enforce best practice, in some others they simplify your code or are obvious corollaries of your not having to deal with memory management. If you violate these rules, you get an immediate compile-time error, not a subtle bug that may become apparent at runtime.
  • You cannot explicitly invoke dealloc, or implement or invoke retainreleaseretainCount, or autorelease.
    The prohibition extends to using @selector(retain)@selector(release), and so on.
    You may implement a dealloc method if you need to manage resources other than releasing instance variables. You do not have to (indeed you cannot) release instance variables, but you may need to invoke [systemClassInstance setDelegate:nil] on system classes and other code that isn’t compiled using ARC.
    Custom dealloc methods in ARC do not require a call to [super dealloc] (it actually results in a compiler error). The chaining to super is automated and enforced by the compiler.
    You can still use CFRetainCFRelease, and other related functions with Core Foundation-style objects (see Managing Toll-Free Bridging).
  • You cannot use NSAllocateObject or NSDeallocateObject.
    You create objects using alloc; the runtime takes care of deallocating objects.
  • You cannot use object pointers in C structures.
    Rather than using a struct, you can create an Objective-C class to manage the data instead.
  • There is no casual casting between id and void *.
    You must use special casts that tell the compiler about object lifetime. You need to do this to cast between Objective-C objects and Core Foundation types that you pass as function arguments. For more details, see Managing Toll-Free Bridging.
  • You cannot use NSAutoreleasePool objects.
    ARC provides @autoreleasepool blocks instead. These have an advantage of being more efficient than NSAutoreleasePool.
  • You cannot use memory zones.
    There is no need to use NSZone any more—they are ignored by the modern Objective-C runtime anyway.
To allow interoperation with manual retain-release code, ARC imposes a constraint on method naming:
  • You cannot give an accessor a name that begins with new. This in turn means that you can’t, for example, declare a property whose name begins with new unless you specify a different getter:
    // Won't work:
    @property NSString *newTitle;
     
    // Works:
    @property (getter=theNewTitle) NSString *newTitle;

ARC Introduces New Lifetime Qualifiers

ARC introduces several new lifetime qualifiers for objects, and weak references. A weak reference does not extend the lifetime of the object it points to, and automatically becomes nil when there are no strong references to the object.
You should take advantage of these qualifiers to manage the object graphs in your program. In particular, ARC does not guard against strong reference cycles(previously known as retain cycles—see Practical Memory Management). Judicious use of weak relationships will help to ensure you don’t create cycles.

Property Attributes

The keywords weak and strong are introduced as new declared property attributes, as shown in the following examples.
// The following declaration is a synonym for: @property(retain) MyClass *myObject;
@property(strong) MyClass *myObject;
 
// The following declaration is similar to "@property(assign) MyClass *myObject;"
// except that if the MyClass instance is deallocated,
// the property value is set to nil instead of remaining as a dangling pointer.
@property(weak) MyClass *myObject;
Under ARC, strong is the default for object types.

Variable Qualifiers

You use the following lifetime qualifiers for variables just like you would, say, const.
__strong
__weak
__unsafe_unretained
__autoreleasing
  • __strong is the default. An object remains “alive” as long as there is a strong pointer to it.
  • __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 specifies a reference that does not keep the referenced object alive and is not set to nil when there are no strong references to the object. If the object it references is deallocated, the pointer is left dangling.
  • __autoreleasing is used to denote arguments that are passed by reference (id *) and are autoreleased on return.
You should decorate variables correctly. When using qualifiers in an object variable declaration, the correct format is:
ClassName * qualifier variableName;
for example:
MyClass * __weak myWeakReference;
MyClass * __unsafe_unretained myUnsafeReference;
Other variants are technically incorrect but are “forgiven” by the compiler. To understand the issue, see http://cdecl.org/.
Take care when using __weak variables on the stack. Consider the following example:
NSString * __weak string = [[NSString alloc] initWithFormat:@"First Name: %@", [self firstName]];
NSLog(@"string: %@", string);
Although string is used after the initial assignment, there is no other strong reference to the string object at the time of assignment; it is therefore immediately deallocated. The log statement shows that string has a null value. (The compiler provides a warning in this situation.)
You also need to take care with objects passed by reference. The following code will work:
NSError *error;
BOOL OK = [myObject performOperationWithError:&error];
if (!OK) {
    // Report the error.
    // ...
However, the error declaration is implicitly:
NSError * __strong e;
and the method declaration would typically be:
-(BOOL)performOperationWithError:(NSError * __autoreleasing *)error;
The compiler therefore rewrites the code:
NSError * __strong error;
NSError * __autoreleasing tmp = error;
BOOL OK = [myObject performOperationWithError:&tmp];
error = tmp;
if (!OK) {
    // Report the error.
    // ...
The mismatch between the local variable declaration (__strong) and the parameter (__autoreleasing) causes the compiler to create the temporary variable. You can get the original pointer by declaring the parameter id __strong * when you take the address of a __strong variable. Alternatively you can declare the variable as__autoreleasing.

Use Lifetime Qualifiers to Avoid Strong Reference Cycles

You can use lifetime qualifiers to avoid strong reference cycles. For example, typically if you have a graph of objects arranged in a parent-child hierarchy and parents need to refer to their children and vice versa, then you make the parent-to-child relationship strong and the child-to-parent relationship weak. Other situations may be more subtle, particularly when they involve block objects.
In manual reference counting mode, __block id x; has the effect of not retaining x. In ARC mode, __block id x; defaults to retaining x (just like all other values). To get the manual reference counting mode behavior under ARC, you could use __unsafe_unretained __block id x;. As the name __unsafe_unretainedimplies, however, having a non-retained variable is dangerous (because it can dangle) and is therefore discouraged. Two better options are to either use __weak (if you don’t need to support iOS 4 or OS X v10.6), or set the __block value to nil to break the retain cycle.
The following code fragment illustrates this issue using a pattern that is sometimes used in manual reference counting.
MyViewController *myController = [[MyViewController alloc] init…];
// ...
myController.completionHandler =  ^(NSInteger result) {
   [myController dismissViewControllerAnimated:YES completion:nil];
};
[self presentViewController:myController animated:YES completion:^{
   [myController release];
}];
As described, instead, you can use a __block qualifier and set the myController variable to nil in the completion handler:
MyViewController * __block myController = [[MyViewController alloc] init…];
// ...
myController.completionHandler =  ^(NSInteger result) {
    [myController dismissViewControllerAnimated:YES completion:nil];
    myController = nil;
};
Alternatively, you can use a temporary __weak variable. The following example illustrates a simple implementation:
MyViewController *myController = [[MyViewController alloc] init…];
// ...
MyViewController * __weak weakMyViewController = myController;
myController.completionHandler =  ^(NSInteger result) {
    [weakMyViewController dismissViewControllerAnimated:YES completion:nil];
};
For non-trivial cycles, however, you should use:
MyViewController *myController = [[MyViewController alloc] init…];
// ...
MyViewController * __weak weakMyController = myController;
myController.completionHandler =  ^(NSInteger result) {
    MyViewController *strongMyController = weakMyController;
    if (strongMyController) {
        // ...
        [strongMyController dismissViewControllerAnimated:YES completion:nil];
        // ...
    }
    else {
        // Probably nothing...
    }
};
In some cases you can use __unsafe_unretained if the class isn’t __weak compatible. This can, however, become impractical for nontrivial cycles because it can be hard or impossible to validate that the __unsafe_unretained pointer is still valid and still points to the same object in question.

ARC Uses a New Statement to Manage Autorelease Pools

Using ARC, you cannot manage autorelease pools directly using the NSAutoreleasePool class. Instead, you use @autoreleasepool blocks:
@autoreleasepool {
     // Code, such as a loop that creates a large number of temporary objects.
}
This simple structure allows the compiler to reason about the reference count state. On entry, an autorelease pool is pushed. On normal exit (break, return, goto, fall-through, and so on) the autorelease pool is popped. For compatibility with existing code, if exit is due to an exception, the autorelease pool is not popped.
This syntax is available in all Objective-C modes. It is more efficient than using the NSAutoreleasePool class; you are therefore encouraged to adopt it in place of using the NSAutoreleasePool.

Patterns for Managing Outlets Become Consistent Across Platforms

The patterns for declaring outlets in iOS and OS X change with ARC and become consistent across both platforms. The pattern you should typically adopt is: outlets should be weak, except for those from File’s Owner to top-level objects in a nib file (or a storyboard scene) which should be strong.
Full details are given in Nib Files in Resource Programming Guide.

Stack Variables Are Initialized with nil

Using ARC, strong, weak, and autoreleasing stack variables are now implicitly initialized with nil. For example:
- (void)myMethod {
    NSString *name;
    NSLog(@"name: %@", name);
}
will log null for the value of name rather than perhaps crashing.

Use Compiler Flags to Enable and Disable ARC

You enable ARC using a new -fobjc-arc compiler flag. You can also choose to use ARC on a per-file basis if it’s more convenient for you to use manual reference counting for some files. For projects that employ ARC as the default approach, you can disable ARC for a specific file using a new -fno-objc-arc compiler flag for that file.
ARC is supported in Xcode 4.2 and later OS X v10.6 and later (64-bit applications) and for iOS 4 and later. Weak references are not supported in OS X v10.6 and iOS 4. There is no ARC support in Xcode 4.1 and earlier.

Managing Toll-Free Bridging

In many Cocoa applications, you need to use Core Foundation-style objects, whether from the Core Foundation framework itself (such as CFArrayRef orCFMutableDictionaryRef) or from frameworks that adopt Core Foundation conventions such as Core Graphics (you might use types like CGColorSpaceRef andCGGradientRef).
The compiler does not automatically manage the lifetimes of Core Foundation objects; you must call CFRetain and CFRelease (or the corresponding type-specific variants) as dictated by the Core Foundation memory management rules (see Memory Management Programming Guide for Core Foundation).
If you cast between Objective-C and Core Foundation-style objects, you need to tell the compiler about the ownership semantics of the object using either a cast (defined in objc/runtime.h) or a Core Foundation-style macro (defined in NSObject.h):
  • __bridge transfers a pointer between Objective-C and Core Foundation with no transfer of ownership.
  • __bridge_retained or CFBridgingRetain casts an Objective-C pointer to a Core Foundation pointer and also transfers ownership to you.
    You are responsible for calling CFRelease or a related function to relinquish ownership of the object.
  • __bridge_transfer or CFBridgingRelease moves a non-Objective-C pointer to Objective-C and also transfers ownership to ARC.
    ARC is responsible for relinquishing ownership of the object.
For example, if you had code like this:
- (void)logFirstNameOfPerson:(ABRecordRef)person {
 
    NSString *name = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    NSLog(@"Person's first name: %@", name);
    [name release];
}
you could replace it with:
- (void)logFirstNameOfPerson:(ABRecordRef)person {
 
    NSString *name = (NSString *)CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
    NSLog(@"Person's first name: %@", name);
}

The Compiler Handles CF Objects Returned From Cocoa Methods

The compiler understands Objective-C methods that return Core Foundation types follow the historical Cocoa naming conventions (see Advanced Memory Management Programming Guide). For example, the compiler knows that, in iOS, the CGColor returned by the CGColor method of UIColor is not owned. You must still use an appropriate type cast, as illustrated by this example:
NSMutableArray *colors = [NSMutableArray arrayWithObject:(id)[[UIColor darkGrayColor] CGColor]];
[colors addObject:(id)[[UIColor lightGrayColor] CGColor]];

Cast Function Parameters Using Ownership Keywords

When you cast between Objective-C and Core Foundation objects in function calls, you need to tell the compiler about the ownership semantics of the passed object. The ownership rules for Core Foundation objects are those specified in the Core Foundation memory management rules (see Memory Management Programming Guide for Core Foundation); rules for Objective-C objects are specified in Advanced Memory Management Programming Guide.
In the following code fragment, the array passed to the CGGradientCreateWithColors function requires an appropriate cast. Ownership of the object returned byarrayWithObjects: is not passed to the function, thus the cast is __bridge.
NSArray *colors = <#An array of colors#>;
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)colors, locations);
The code fragment is shown in context in the following method implementation. Notice also the use of Core Foundation memory management functions where dictated by the Core Foundation memory management rules.
- (void)drawRect:(CGRect)rect {
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
    CGFloat locations[2] = {0.0, 1.0};
    NSMutableArray *colors = [NSMutableArray arrayWithObject:(id)[[UIColor darkGrayColor] CGColor]];
    [colors addObject:(id)[[UIColor lightGrayColor] CGColor]];
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)colors, locations);
    CGColorSpaceRelease(colorSpace);  // Release owned Core Foundation object.
    CGPoint startPoint = CGPointMake(0.0, 0.0);
    CGPoint endPoint = CGPointMake(CGRectGetMaxX(self.bounds), CGRectGetMaxY(self.bounds));
    CGContextDrawLinearGradient(ctx, gradient, startPoint, endPoint,
                                kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
    CGGradientRelease(gradient);  // Release owned Core Foundation object.
}

Common Issues While Converting a Project

When migrating existing projects, you are likely to run into various issues. Here are some common issues, together with solutions.
  • You can’t invoke retainrelease, or autorelease.
    This is a feature. You also can’t write:
    while ([x retainCount]) { [x release]; }
  • You can’t invoke dealloc.
    You typically invoke dealloc if you are implementing a singleton or replacing an object in an init methods. For singletons, use the shared instance pattern. Ininit methods, you don't have to call dealloc anymore, because the object will be freed when you overwrite self.
  • You can’t use NSAutoreleasePool objects.
    Use the new @autoreleasepool{} construct instead. This forces a block structure on your autorelease pool, and is about six times faster thanNSAutoreleasePool@autoreleasepool even works in non-ARC code. Because @autoreleasepool is so much faster than NSAutoreleasePool, many old “performance hacks” can simply be replaced with unconditional @autoreleasepool.
    The migrator handles simple uses of NSAutoreleasePool, but it can't handle complex conditional cases, or cases where a variable is defined inside the body of the new @autoreleasepool and used after it.
  • ARC requires you to assign the result of [super init] to self in init methods.
    The following is invalid in ARC init methods:
    [super init];
    The simple fix is to change it to:
    self = [super init];
    The proper fix is to do that, and check the result for nil before continuing:
    self = [super init];
    if (self) {
       ...
  • You can’t implement custom retain or release methods.
    Implementing custom retain or release methods breaks weak pointers. There are several common reasons for wanting to provide custom implementations:
    • Performance.
      Please don’t do this any more; the implementation of retain and release for NSObject is much faster now. If you still find problems, please file bugs.
    • To implement a custom weak pointer system.
      Use __weak instead.
    • To implement singleton class.
      Use the shared instance pattern instead. Alternatively, use class instead of instance methods, which avoids having to allocate the object at all.
  • “Assigned” instance variables become strong.
    Before ARC, instance variables were non-owning references—directly assigning an object to an instance variable did not extend the lifetime of the object. To make a property strong, you usually implemented or synthesized accessor methods that invoked appropriate memory management methods; in contrast, you may have implemented accessor methods like those shown in the following example to maintain a weak property.
    @interface MyClass : Superclass {
        id thing; // Weak reference.
    }
    // ...
    @end
     
    @implementation MyClass
    - (id)thing {
        return thing;
    }
    - (void)setThing:(id)newThing {
        thing = newThing;
    }
    // ...
    @end
    With ARC, instance variables are strong references by default—assigning an object to an instance variable directly does extend the lifetime of the object. The migration tool is not able to determine when an instance variable is intended to be weak. To maintain the same behavior as before, you must mark the instance variable as being weak, or use a declared property.
    @interface MyClass : Superclass {
        id __weak thing;
    }
    // ...
    @end
     
    @implementation MyClass
    - (id)thing {
        return thing;
    }
    - (void)setThing:(id)newThing {
        thing = newThing;
    }
    // ...
    @end
    Or:
    @interface MyClass : Superclass
    @property (weak) id thing;
    // ...
    @end
     
    @implementation MyClass
    @synthesize thing;
    // ...
    @end
  • You can't use strong ids in C structures.
    For example, the following code won’t compile:
    struct X { id x; float y; };
    This is because x defaults to strongly retained and the compiler can’t safely synthesize all the code required to make it work correctly. For example, if you pass a pointer to one of these structures through some code that ends up doing a free, each id would have to be released before the struct is freed. The compiler cannot reliably do this, so strong ids in structures are disallowed completely in ARC mode. There are a few possible solutions:
    1. Use Objective-C objects instead of structs.
      This is considered to be best practice anyway.
    2. If using Objective-C objects is sub-optimal, (maybe you want a dense array of these structs) then consider using a void* instead.
      This requires the use of the explicit casts, described below.
    3. Mark the object reference as __unsafe_unretained.
      This approach may be useful for the semi-common patterns like this:
      struct x { NSString *S;  int X; } StaticArray[] = {
        @"foo", 42,
        @"bar, 97,
      ...
      };
      You declare the structure as:
      struct x { NSString * __unsafe_unretained S; int X; }
      This may be problematic and is unsafe if the object could be released out from under the pointer, but it is very useful for things that are known to be around forever like constant string literals.
  • You can’t directly cast between id and void* (including Core Foundation types).
    This is discussed in greater detail in Managing Toll-Free Bridging.

Frequently Asked Questions

How do I think about ARC? Where does it put the retains/releases?
Try to stop thinking about where the retain/release calls are put and think about your application algorithms instead. Think about “strong and weak” pointers in your objects, about object ownership, and about possible retain cycles.
Do I still need to write dealloc methods for my objects?
Maybe.
Because ARC does not automate malloc/free, management of the lifetime of Core Foundation objects, file descriptors, and so on, you still free such resources by writing a dealloc method.
You do not have to (indeed cannot) release instance variables, but you may need to invoke [self setDelegate:nil] on system classes and other code that isn’t compiled using ARC.
dealloc methods in ARC do not require—or allow—a call to [super dealloc]; the chaining to super is handled and enforced by the runtime.
Are retain cycles still possible in ARC?
Yes.
ARC automates retain/release, and inherits the issue of retain cycles. Fortunately, code migrated to ARC rarely starts leaking, because properties already declare whether the properties are retaining or not.
How do blocks work in ARC?
Blocks “just work” when you pass blocks up the stack in ARC mode, such as in a return. You don’t have to call Block Copy any more.
The one thing to be aware of is that NSString * __block myString is retained in ARC mode, not a possibly dangling pointer. To get the previous behavior, use__block NSString * __unsafe_unretained myString or (better still) use __block NSString * __weak myString.
Can I develop applications for OS X with ARC using Snow Leopard?
No. The Snow Leopard version of Xcode 4.2 doesn’t support ARC at all on OS X, because it doesn’t include the 10.7 SDK. Xcode 4.2 for Snow Leopard does support ARC for iOS though, and Xcode 4.2 for Lion supports both OS X and iOS. This means you need a Lion system to build an ARC application that runs on Snow Leopard.
Can I create a C array of retained pointers under ARC?
Yes, you can, as illustrated by this example:
// Note calloc() to get zero-filled memory.
__strong SomeClass **dynamicArray = (__strong SomeClass **)calloc(entries, sizeof(SomeClass *));
for (int i = 0; i < entries; i++) {
     dynamicArray[i] = [[SomeClass alloc] init];
}
 
// When you're done, set each entry to nil to tell ARC to release the object.
for (int i = 0; i < entries; i++) {
     dynamicArray[i] = nil;
}
free(dynamicArray);
There are a number of aspects to note:
  • You will need to write __strong SomeClass ** in some cases, because the default is __autoreleasing SomeClass **.
  • The allocated memory must be zero-filled.
  • You must set each element to nil before freeing the array (memset or bzero will not work).
  • You should avoid memcpy or realloc.
Is ARC slow?
It depends on what you’re measuring, but generally “no.” The compiler efficiently eliminates many extraneous retain/release calls and much effort has been invested in speeding up the Objective-C runtime in general. In particular, the common “return a retain/autoreleased object” pattern is much faster and does not actually put the object into the autorelease pool, when the caller of the method is ARC code.
One issue to be aware of is that the optimizer is not run in common debug configurations, so expect to see a lot more retain/release traffic at -O0 than at -Os.
Does ARC work in ObjC++ mode?
Yes. You can even put strong/weak ids in classes and containers. The ARC compiler synthesizes retain/release logic in copy constructors and destructors etc to make this work.
Which classes don’t support weak references?
You cannot currently create weak references to instances of the following classes:
NSATSTypesetterNSColorSpaceNSFontNSMenuViewNSParagraphStyleNSSimpleHorizontalTypesetter, and NSTextView.
For declared properties, you should use assign instead of weak; for variables you should use __unsafe_unretained instead of __weak.
In addition, you cannot create weak references from instances of NSHashTableNSMapTable, or NSPointerArray under ARC.
What do I have to do when subclassing NSCell or another class that uses NSCopyObject?
Nothing special. ARC takes care of cases where you had to previously add extra retains explicitly. With ARC, all copy methods should just copy over the instance variables.
Can I opt out of ARC for specific files?
Yes.
When you migrate a project to use ARC, the -fobjc-arc compiler flag is set as the default for all Objective-C source files. You can disable ARC for a specific class using the -fno-objc-arc compiler flag for that class. In Xcode, in the target Build Phases tab, open the Compile Sources group to reveal the source file list. Double-click the file for which you want to set the flag, enter -fno-objc-arc in the pop-up panel, then click Done.
../Art/fno-objc-arc.png
Is GC (Garbage Collection) deprecated on the Mac?
Garbage collection is deprecated in OS X Mountain Lion v10.8, and will be removed in a future version of OS X. Automatic Reference Counting is the recommended replacement technology. To aid in migrating existing applications, the ARC migration tool in Xcode 4.3 and later