Monday, 9 November 2015

Dlog

//
// Prefix header for all source files
//

#ifdef __OBJC__
#endif

#ifndef DLog
    #if kDebug
        #define DLog( s, ... ) NSLog( @"\n\n************************************* DEBUG *************************************\n\t<%p %@:(%d)>\n\n\t%@\n****************************************************************************\n\n", self, \
        [[NSString stringWithUTF8String:__FUNCTION__] lastPathComponent], __LINE__, \
        [NSString stringWithFormat:(s), ##__VA_ARGS__] )
    #else
        #define DLog( s, ... )
    #endif
#endif

#ifndef DStep
    #if kDebug
        #define DStep( s, ... ) NSLog( @"\n\n************************************* DEBUG *************************************\n\t%@\n*********************************************************************************\n\n", [NSString stringWithFormat:(s), ##__VA_ARGS__])
    #else
        #define DStep( s, ... )
    #endif
#endif

Sunday, 8 November 2015

Interview Queations 6 Memory Management

1) What is the memory management?
        It allocates and reallocates memory and find out memory leaks.
2) What the difference is between retain and release?
        Retain: Increment index by 1
        Release: decrement index by 1 

     The default auto-release pool is drained every time through the run loop, not once per application lifecycle. So as soon as your current stack of method calls completes, and you're back waiting for a UI event, the pool is drained.


3) Can you explain what happens when you call autorelease on an object?

When you send an object a autorelease message, its retain count is decremented by 1 at some stage in the future. The object is added to an autorelease pool on the current
thread. The main thread loop creates an autorelease pool at the beginning of the function, and release it at the end. This establishes a pool for the lifetime of the task. However, this also means that any autoreleased objects created during the lifetime of the task are not disposed of until the task completes. This may lead to the task
ʼs memory footprint increasing unnecessarily. You can also consider creating pools with a narrower scope or use NSOperationQueue with itʼs own autorelease pool. (Also important – You only release or autorelease objects you own.)  



4) Explain the correct way to manage Outlets memory

Create them as properties in the header that are retained. In the viewDidUnload set the outlets to nil(i.e self.outlet = nil). Finally in dealloc make sure to release the outlet.

5)Can you just explain about memory management in iOS?

Memory management is the programming discipline of managing the life cycles of objects and freeing them when they are no longer needed. Managing object memory is a matter of performance; if an application doesn’t free unneeded objects, its memory footprint grows and performance suffers. Memory management in a Cocoa application that doesn’t use garbage collection is based on a reference counting model. When you create or copy an object, its retain count is 1. Thereafter other objects may express an ownership interest in your object, which increments its retain count. The owners of an object may also relinquish their ownership interest in it, which decrements the retain count. When the retain count becomes zero, the object is deallocated (destroyed).

To assist you in memory management, Objective-C gives you methods and mechanisms that you must use in conformance with a set of rules.



6) What is Automatic Reference Counting (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.


7) Why dynamic memory allocation is required?
            Dynamic Memory allocation - memory is allocated during run-time in heap. This is used when the amount(size) of memory is variable and is known only during run-time. Dynamic allocation is achieved using certain functions like malloc(), calloc(), realloc(), free in C and "new", "delete" in C++.
Static Memory Allocation - memory allocated at compile time in stack or other data segments. This is used when the amount(size) of memory is static/constant and is known during compile-time.

8) Given an object of an unknown type, how would you determine its class? How would you
Check to see if it conforms to a given protocol? How would you check to see if it responds to
a given message/selector?
               [theObject respondsToSelector:@selector(theSelector)]
The most common pattern for this problem in Cocoa/Cocoa Touch is to define a protocol. A protocol is a collection of methods that can be implemented by any object.If you make ClassA and ClassB conform to a protocol containing the methods you need them to respond to then you don't need to worry about which type of object you get. The idea is "if it looks like a duck and quacks like a duck, then it's probably a duck".
You can use dynamic typing and create your objects depending on the outcome of your query, but ensure that the resulting object conforms to a particular protocol, like so:
id <MyProtocol> myObject;



if (YES)

    myObject = [[ClassA alloc] init];

else

    myObject = [[ClassB alloc] init];



[myObject myMethod];

[myObject release];


Interview Queations 5 Attributs

1) What is atomic and nonatomic? Which one is safer? Which one is default?

            Both are same unless we use our setter and getter methods. If we create our own setter and getter method, then atomic is useful in thread processing, but it is slow. Nonatomic does not give guarantee on thread processing but it is fast.

2) What is the difference between copy & retain? When can we go for copy and when can we go for retain? 

      Retaining and copying are two different things, the first is conceptually call-by-reference while the second is call-by-value.

 

3) What is @synthesize?
@property and @synthesize provides the getter and setter (accessors) methods rather than you having to write it out yourself. The declaration is made with @property and it is implemented with @synthesize.
4) Explain deep copy and shallow copy?
newArary = oldArray isn't a copy at all. You end up with two pointers pointing to the exact same array.
newArray = [NSMutableArray arrayWithArray:oldArray]; is a shallow copy. You end up with two distinct arrays, so if you were to remove or add items from one array, it wouldn't affect the other array. However, the items in the two arrays are identical. If the first element of oldArray were an NSMutableDictionary and you added a key to it, you'd see that change on the first element of newArray as well (since those two objects are the same).
To do a deep copy, you would have to make a new array, and each element of the new array would be a deep copy of the corresponding element of the old array. (Yes, that definition is recursive).
5) Difference between retain and copy?
In a general setting, retaining an object will increase its retain count by one. This will help keep the object in memory and prevent it from being blown away. What this means is that if you only hold a retained version of it, you share that copy with whomever passed it to you.
Copying an object, however you do it, should create another object with duplicate values. Think of this as a clone. You do NOT share the clone with whomever passed it to you.
When dealing with NSStrings in particular, you may not be able to assume that whoever is giving you an NSString is truly giving you an NSString. Someone could be handing you a subclass (NSMutableString, in this case) which means that they could potentially modify the values under the covers. If your application depends on the value passed in, and someone changes it on you, you can run into trouble.
Retaining and copying are two different things, the first is conceptually call-by-reference while the second is call-by-value.
If you ask me, copy should be used for NSString. If it's Mutable, then it gets copied. If it's not, then it just gets retained. Exactly the semantics that you want in an app (let the type do what's best).

6) What is atomic and non atomic?
Basically, if you say nonatomic, and you generate the accessors using @synthesize, then if multiple threads try to change/read the property at once, badness can happen. You can get partially-written values or over-released/retained objects, which can easily lead to crashes. (This is potentially a lot faster than an atomic accessor, though.)
If you use the default (which is atomic; there's no keyword for this), then the @synthesized methods use an object-level lock to ensure that multiple reads/writes to a property are serialized. As the Apple docs point out, this doesn't mean the whole object is thread-safe, but the property reads/writes are.
Of course, if you implement your own accessors rather than using @synthesize, I think these declarations do nothing except express your intent as to whether the property is implemented in a threadsafe manner.

7) NULL or nil?
In Cocoa both of them are typedef to zero. nil is an object pointer, whereas NULL is a c pointer.  If you want to set char * to 0 then you would set it to NULL and if you want to set a view controller to 0 then you would set it to nil. Cocoa also gives us another typedef  called “Nil” (notice the case) which is class pointer. Now you know when to use the correct null pointer.

8) What exactly does @synthesize do?
@synthesize keyword to tell the compiler that it should generate the setter and/or getter methods for the property if you do not supply them within the @implementation block.
9) What is atomic and non-atomic?
nonatomic -  if  you generate the accessors using @synthesize, then if multiple threads try to change/read the property at once, badness can happen. You can get partially-written values or over-released/retained objects, which can easily lead to crashes. (This is potentially a lot faster than an atomic accessor, though.)  
atomic – If you use the default (which is atomic; there’s no keyword for this), then the @synthesized methods use an object-level lock to ensure that multiple reads/writes to a property are serialized. As the Apple docs point out, this doesn’t mean the whole object is thread-safe, but the property reads/writes are. Of course, if you implement your own accessors rather than using @synthesize, I think these declarations do nothing except express your intent as to whether the property is implemented in a threadsafe manner.



 

 

 

Interview Queations 4 Desing Patterns

1) How can we achieve singleton pattern in iOS?

 

The Singleton design pattern ensures a class only has one instance, and provides a global point of access to it. The class keeps track of its sole instance and ensures that no other instance can be created. Singleton classes are appropriate for situations where it makes sense for a single object to provide access to a global resource.
Several Cocoa framework classes are singletons. They include NSFileManager, NSWorkspace, NSApplication, and, in UIKit, UIApplication. A process is limited to one instance of these classes. When a client asks the class for an instance, it gets a shared instance, which is lazily created upon the first request.

2) What is delegate pattern in iOS?

 

Delegation is a mechanism by which a host object embeds a weak reference (weak in the sense that it’s a simple pointer reference, unretained) to another object—its delegate—and periodically sends messages to the delegate when it requires its input for a task. The host object is generally an “off-the-shelf” framework object (such as an NSWindow or NSXMLParser object) that is seeking to accomplish something, but can only do so in a generic fashion. The delegate, which is almost always an instance of a custom class, acts in coordination with the host object, supplying program-specific behavior at certain points in the task (see Figure). Thus delegation makes it possible to modify or extend the behavior of another object without the need for subclassing.


1. MVC – Introduction

As implied with the name, the MVC software design pattern refers to three separate roles: the model, the view and the controller.
The idea is that the objects in your application will take on these roles and work together to create and manage the user interface. Not all objects will assume one of these 3 roles; For example you might have a class that contains a bunch of helper methods however, the model, view and controller roles are the central actors to making your app function.
The Model
The model represents the data in your application. It’s responsible for sorting, validating and organizing your data.
The View
The view is the user interface or what the user sees and interacts with.
You can create views programmatically through code using Apple classes such as UIView or you can create a XIB file to represent the view and visually layout your elements through Interface Builder.
The Controller
The controller manages the communication between the view and the model. It takes the data from the model and communicates it to the view for display.
In the same vein, the controller also takes the changed data (due to user interaction or something else) and communicates it back to the model.
The Model And View Never Talk To Each Other
They shouldn’t even know about each other in the ideal case.
The beauty of this modular architecture is that the separation of roles allow us to make modifications easily with less bugs.
For example, if in the future, you need to make a change to the way the data is fetched or organized, all you need to do is switch out the model. As long as you keep the interface of the model the same (the header file), then the views and controllers will be none the wiser.

Here’s a diagram illustrating what we’ve talked about:

Model View Controller Diagram










Interview Queations 3

1)What are categories in iOS?

A Category is a feature of the Objective-C language that enables you to add methods (interface and implementation) to a class without having to make a subclass. There is no runtime difference—within the scope of your program—between the original methods of the class and the methods added by the category. The methods in the category become part of the class type and are inherited by all the class’s subclasses.
As with delegation, categories are not a strict adaptation of the Decorator pattern, fulfilling the intent but taking a different path to implementing that intent. The behavior added by categories is a compile-time artifact, and is not something dynamically acquired. Moreover, categories do not encapsulate an instance of the class being extended.

2) What is Delegation in iOS?

Delegation is a design pattern in which one object sends messages to another object—specified as its delegate—to ask for input or to notify it that an event is occurring. Delegation is often used as an alternative to class inheritance to extend the functionality of reusable objects. For example, before a window changes size, it asks its delegate whether the new size is ok. The delegate replies to the window, telling it that the suggested size is acceptable or suggesting a better size. (For more details on window resizing, see the windowWillResize:toSize: message.)
Delegate methods are typically grouped into a protocol. A protocol is basically just a list of methods. The delegate protocol specifies all the messages an object might send to its delegate. If a class conforms to (or adopts) a protocol, it guarantees that it implements the required methods of a protocol. (Protocols may also include optional methods).
In this application, the application object tells its delegate that the main startup routines have finished by sending it the applicationDidFinishLaunching: message. The delegate is then able to perform additional tasks if it wants. 


3) What are all the difference between categories and subclasses? Why should we go to subclasses?

Category is a feature of the Objective-C language that enables you to add methods (interface and implementation) to a class without having to make a subclass. There is no runtime difference—within the scope of your program—between the original methods of the class and the methods added by the category. The methods in the category become part of the class type and are inherited by all the class’s subclasses.
As with delegation, categories are not a strict adaptation of the Decorator pattern, fulfilling the intent but taking a different path to implementing that intent. The behavior added by categories is a compile-time artifact, and is not something dynamically acquired. Moreover, categories do not encapsulate an instance of the class being extended.
The Cocoa frameworks define numerous categories, most of them informal protocols . Often they use categories to group related methods. You may implement categories in your code to extend classes without subclassing or to group related methods. However, you should be aware of these caveats:
You cannot add instance variables to the class.
If you override existing methods of the class, your application may behave unpredictably.

4) What is notification in iOS?

The notification mechanism of Cocoa implements one-to-many broadcast of messages based on the Observer pattern. Objects in a program add themselves or other objects to a list of observers of one or more notifications, each of which is identified by a global string (the notification name). The object that wants to notify other objects—the observed object—creates a notification object and posts it to a notification center. The notification center determines the observers of a particular notification and sends the notification to them via a message. The methods invoked by the notification message must conform to a certain single-parameter signature. The parameter of the method is the notification object, which contains the notification name, the observed object, and a dictionary containing any supplemental information.
Posting a notification is a synchronous procedure. The posting object doesn't regain control until the notification center has broadcast the notification to all observers. For asynchronous behavior, you can put the notification in a notification queue; control returns immediately to the posting object and the notification center broadcasts the notification when it reaches the top of the queue.
Regular notifications—that is, those broadcast by the notification center—are intraprocess only. If you want to broadcast notifications to other processes, you can use the istributed notification center and its related API. 

5) What is the difference between delegates and notifications?

We can use notifications for a variety of reasons. For example, you could broadcast a notification to change how user-interface elements display information based on a certain event elsewhere in the program. Or you could use notifications as a way to ensure that objects in a document save their state before the document window is closed. The general purpose of notifications is to inform other objects of program events so they can respond appropriately.
But objects receiving notifications can react only after the event has occurred. This is a significant difference from delegation. The delegate is given a chance to reject or modify the operation proposed by the delegating object. Observing objects, on the other hand, cannot directly affect an impending operation.

 6)What is protocol?
A protocol is an important language feature in Objective-C. Protocols provide, among other things, the ability to realize multiple inheritance in a single-inheritance language.
Think of a protocol as an interface in the Java language. Just as classes in Java can implement multiple interfaces, so can classes in Objective-C adopt multiple protocols.
A protocol is just a list of methods. Each method in this list can be tagged as either required (@required, the default) or optional (@optional). If a class adopts a protocol, it must implement at least all required methods in that protocol
7) Difference between protocol and delegate?
A protocol is an interface that a class can conform to, meaning that class implements the listed methods. A class can be tested for conformance to a protocol at compile-time and also at run-time using the conformsToProtocol:.. NSObject method.
A delegate is a more abstract term that refers to the Delegation Design Patten. Using this design pattern, a class would have certain operations that it delegates out (perhaps optionally). Doing so creates an alternative to subclassing by allowing specific tasks to be handled in an application-specific manner, which would be implemented by a delegate.
They are related terms because you often see a Protocol created for the purpose of delegation. If I wanted to allow a delegate to sort something, I'd create a Protocol with a required method listed such as "sortMyCoolStuff:.." and I would require the delegate to implement it. That way, within class that supports calling to a delegate, I can accept a pointer to a delegate and then can say "if that delegate conforms to myCoolProtocol, I know it implements sortMyCoolStuff, so it's safe to call that method instead of doing my built in behavior"

Interview Queations 2


1) Whats the NSCoder class used for?

NSCoder is an abstractClass which represents a stream of data. They are used in Archiving and Unarchiving objects. NSCoder objects are usually used in a method that is being implemented so that the class conforms to the protocol. (which has something like encodeObject and decodeObject methods in them). 
 

2) Whats an NSOperationQueue and how/would you use it?

The NSOperationQueue class regulates the execution of a set of NSOperation objects. An operation queue is generally used to perform some asynchronous operations on a background thread so as not to block the main thread.  
 

3) Explain the correct way to manage Outlets memory

Create them as properties in the header that are retained. In the viewDidUnload set the outlets to nil(i.e self.outlet = nil). Finally in dealloc make sure to release the outlet.

4)What is Automatic Reference Counting (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.
 

5) Multitasking support is available from which version?

 iOS 4.0
 

6) How many bytes we can send to apple push notification server?

256bytes.
 

7) What the difference is between retain & assign?

Assign creates a reference from one object to another without increasing the source's retain count.
if (_variable != object) {     [_variable release];     _variable = nil;     _variable = object;   }
Retain creates a reference from one object to another and increases the retain count of the source object.
if (_variable != object) {     [_variable release];     _variable = nil;     _variable = [object retain];   }
 

8)Why do we need to use @Synthesize?

We can use generated code like nonatomic, atmoic, retain without writing any lines of code. We also have getter and setter methods. To use this, you have 2 other ways: @synthesize or @dynamic: @synthesize, compiler will generate the getter and setter automatically for you, @dynamic: you have to write them yourself.
@property is really good for memory management, for example: retain.

9)How can you do retain without @property?
if (_variable != object) {     [_variable release];     _variable = nil;     _variable = [object retain];   } 
 
10)How can you use it with @property?
self.variable = object; 
When we are calling the above line, we actually call the setter like [self setVariable:object] and then the generated setter will do its job 

About AutoRealease Call


When you send an object a autorelease message, its retain count is decremented by 1 at some stage in the future. The object is added to an autorelease pool on the current
thread. The main thread loop creates an autorelease pool at the beginning of the function, and release it at the end. This establishes a pool for the lifetime of the task. However, this also means that any autoreleased objects created during the lifetime of the task are not disposed of until the task completes. This may lead to the task
ʼs memory footprint increasing unnecessarily. You can also consider creating pools with a narrower scope or use NSOperationQueue with itʼs own autorelease pool. (Also important – You only release or autorelease objects you own.)