Thursday, December 31, 2015

@class vs. #import

@class MyViewController;

Is a forward declaration for the object MyViewController. It is used when you just need to tell the compiler about an object type but have no need to include the header file.

If however you need to create an object of this type and invoke methods on it, you will need to:

#import "MyViewController.h"

But normally this is done in the .m file.

An additional use of forward declarations is when you define a @protocol in the same header file as an object that uses it.

@protocol MyProtocolDelegate; //forward declaration

@interface MyObject {
    id<MyProtocolDelegate> delegate;
    ...
}
...
@end

@protocol MyProtocolDelegate
    ... //protocol definition
@end

In the above example the compiler needs to know that the @protocol MyProtocolDelegate is valid before it can compile the MyObject object.

Simply moving the protocol definition above MyObject definition would also work.

Convert Project from Storyboard to Xib

Objective C

Step 1)
//Add below code in  AppDelegate.h
@property (retain, nonatomic) UIWindow *window;
@property (nonatomic,retain) UINavigationController *navigationController;

Step 2)
Create New file ViewController subclass of UIViewController with Xib

Step 3)
//Add below code in  AppDelegate.m
self.window=[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

ViewController *viewController=[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
return YES;

Step 4)
Delete “Main storyboard file base name” line from info.plist file

Step 5)
Run Project

Swift

In didFinishLaunchingWithOptions Method in Appdelegate


        window = UIWindow(frame: UIScreen.mainScreen().bounds)
      
        let mainViewController = HomeViewController(nibName: "HomeViewController", bundle: nil)
      
        let navigationController = UINavigationController(rootViewController: mainViewController)
      
        window?.rootViewController = navigationController
        window?.makeKeyAndVisible()
      
        return true

Tuesday, December 29, 2015

Explain: In-App Purchase

In-App Purchase allows you to embed a store inside your app using the Store Kit framework.

This framework connects to the App Store on your app’s behalf to securely process payments from users, prompting them to authorize payment.
The framework then notifies your app, which provides the purchased items to users. Use In-App Purchase to collect payment for additional features and content.

Type of In-App Purchase::
Consumable products: Items that get used up over the course of running your app. Examples include minutes for a Voice over IP app and one-time services such as voice transcription.

Non-consumable products: Items that remain available to the user indefinitely on all of the user’s devices. They’re made available to all of the user’s devices. Examples include content, such as books and game levels, and additional app functionality.

Auto-renewable subscriptions: Episodic content. Like non-consumable products, auto-renewable subscriptions remain available to the user indefinitely on all of the user’s devices. Unlike non-consumable products, auto-renewable subscriptions have an expiration date. You deliver new content regularly, and users get access to content published during the time period their subscription is active. When an auto-renewable subscription is about to expire, the system automatically renews it on the user’s behalf.

Non-renewable subscriptions: Subscriptions that don’t involve delivering episodic content. Examples include access to a database of historic photos or a collection of flight maps. It’s your app’s responsibility to make the subscription available on all of the user’s devices and to let users restore the purchase. This product type is often used when your users already have an account on your server that you can use to identify them when restoring content. Expiration and the duration of the subscription are also left to your app (or your server) to implement and enforce.

Free subscriptions: A way to put free subscription content in Newsstand. After a user signs up for a free subscription, the content is available on all devices associated with the user’s Apple ID. Free subscriptions don’t expire and can be offered only in Newsstand-enabled apps.

Monday, December 28, 2015

NSThread vs GCD

Migrating Away from Threads

The idea is that you eliminate work on your part, since the paradigm fits MOST code more easily.
It reduces the memory penalty your application pays for storing thread stacks in the application’s memory space.

It eliminates the code needed to create and configure your threads.
It eliminates the code needed to manage and schedule work on threads.
It simplifies the code you have to write.

Empirically, using GCD-type locking instead of @synchronized is about 80% faster or more, though micro-benchmarks may be deceiving. Read more here, though I think the advice to go async with writes does not apply in many cases, and it's slower (but it's asynchronous).

Advantages of Threads

Why would you continue to use Threads? From the same document:

It is important to remember that queues are not a panacea for replacing threads. The asynchronous programming model offered by queues is appropriate in situations where latency is not an issue. Even though queues offer ways to configure the execution priority of tasks in the queue, higher execution priorities do not guarantee the execution of tasks at specific times. Therefore, threads are still a more appropriate choice in cases where you need minimal latency, such as in audio and video playback.

Another place where I haven't personally found an ideal solution using queues is daemon processes that need to be constantly rescheduled. Not that you cannot reschedule them, but looping within a NSThread method is simpler (I think). Edit: Now I'm convinced that even in this context, GCD-style locking would be faster, and you could also do a loop within a GCD-dispatched operation.

Blocks

Please read from below link.

Click here


NSURLConnection

Please read from below link.

Click Here

Where are objects and variables stored in Objective-C (Heap or Stack)?

In Objective-C, objects are usually created on the heap:

    NSObject *obj = [[NSObject alloc] init];

The storage for the obj variable itself is on the stack, but the object it points to is in the heap. The [NSObject alloc] call allocates a chunk of heap memory, and fills it out to match the layout needed for an NSObject.

A stack object is just an object where the memory for that object is allocated on the stack. Objective-C doesn't have any support for this directly

Objective-C supports stack objects only for Blocks.

What is syncronous and asynchronous call?

A synchronous process is invoked by a request/response operation, and the result of the process is returned to the caller immediately via this operation.

An asynchronous process is invoked by a one-way operation and the result and any faults are returned by invoking other one-way operations. The process result is returned to the caller via a callback operation.

For example, you can think of a synchronous process as a telephone, and an asynchronous process as the postal system. When you are having a conversation on the phone, you send and receive messages instantaneously using the same connection. If you were to send the same message in a letter via the postal service, it would be delivered in one manner, and its response returned in another.

Abstract class in cocoa

Cocoa doesn’t provide anything called abstract.  We can create a class abstract which gets check only at runtime, compile time this is not checked.
@interface AbstractClass : NSObject
@end
@implementation AbstractClass
+ (id)alloc{
    if (self == [AbstractClass class]) {
        NSLog(@"Abstract Class cant be used");
    }
    return [super alloc];
@end


Abstract Class

Abstract Class is a class which contains atleast one Pure Virtual function in it. Abstract classes are used to provide an Interface for its sub classes. Classes inheriting an Abstract Class must provide definition to the pure virtual function, otherwise they will also become abstract class.

Characteristics of Abstract Class

    Abstract class cannot be instantiated, but pointers and refrences of Abstract class type can be created.
    Abstract class can have normal functions and variables along with a pure virtual function.
    Abstract classes are mainly used for Upcasting, so that its derived classes can use its interface.
    Classes inheriting an Abstract Class must implement all pure virtual functions, or else they will become Abstract too.

Pure Virtual Functions

Pure virtual Functions are virtual functions with no definition. They start with virtual keyword and ends with = 0. Here is the syntax for a pure virtual function,

virtual void f() = 0;

Example of Abstract Class

class Base          //Abstract base class
{
 public:
 virtual void show() = 0;            //Pure Virtual Function
};

class Derived:public Base
{
 public:
 void show()
 { cout << "Implementation of Virtual Function in Derived class"; }
};

int main()
{
 Base obj;       //Compile Time Error
 Base *b;
 Derived d;
 b = &d;
 b->show();
}

Output :

Implementation of Virtual Function in Derived class

In the above example Base class is abstract, with pure virtual show() function, hence we cannot create object of base class.

Why can't we create Object of Abstract Class ?
When we create a pure virtual function in Abstract class, we reserve a slot for a function in the VTABLE(studied in last topic), but doesn't put any address in that slot. Hence the VTABLE will be incomplete.

As the VTABLE for Abstract class is incomplete, hence the compiler will not let the creation of object for such class and will display an errror message whenever you try to do so.

Pure Virtual definitions

    Pure Virtual functions can be given a small definition in the Abstract class, which you want all the derived classes to have. Still you cannot create object of Abstract class.
    Also, the Pure Virtual function must be defined outside the class definition. If you will define it inside the class definition, complier will give an error. Inline pure virtual definition is Illegal.

class Base          //Abstract base class
{
 public:
 virtual void show() = 0;            //Pure Virtual Function
};

void Base :: show()         //Pure Virtual definition
{
 cout << "Pure Virtual definition\n";
}

class Derived:public Base
{
 public:
 void show()
 { cout << "Implementation of Virtual Function in Derived class"; }
};

int main()
{
 Base *b;
 Derived d;
 b = &d;
 b->show();
}

Output :

Pure Virtual definition
Implementation of Virtual Function in Derived class
 

What are Web Services?

  • Web services are application components
  • Web services communicate using open protocols
  • Web services are self-contained and self-describing
  • Web services can be discovered using UDDI
  • Web services can be used by other applications
  • XML is the basis for Web services
The basic Web services platform is XML + HTTP.

XML provides a language which can be used between different platforms and programming languages and still express complex messages and functions.

The HTTP protocol is the most used Internet protocol.

Web services platform elements:

  • SOAP (Simple Object Access Protocol)
  • UDDI (Universal Description, Discovery and Integration)
  • WSDL (Web Services Description Language)

In cocoa, NSURLConnection and NSURLRequest are used for this.

Copy vs mutableCopy

copy always creates an immutable copy.
mutableCopy always creates a mutable copy.

Retain cycle or Retain loop

When object A retains object B, and object B retains A. Then Retain cycle happens. To overcome this use “close” method.

Objective-C's garbage collector (when enabled) can also delete retain-loop groups  but this is not relevant on the iPhone, where Objective-C garbage collection is not supported.

Difference between Database,coreData and Sqlite

Database
Its primary function is to store and fetch data.
It operates on data stored on disk.
It can store "dumb" data.
It can be transactional, thread-safe, multi-user.
Can drop tables and edit data without loading into memory.
Perpetually saved to disk.
Can be slowto create millions of new rows.
Offers data constraints like "unique" keys.

CoreData
Its primary function is graph management.
It can operate on objects stored in memory.
Works with fully-fledged objects that self-manage many of their behaviour and can be subclassed and customised for further behaviours.
Non-transactional, single threaded, single user.
It only operates in memory.
Requires a save process.
Can create millions of new objects in-memory very quickly.
Leaves data constraints to the business logic side of the program.

Sqlite
To implement its graph management, Core Data happens to use sqlite as a disk store.
It could have been implemented using a different relational database or even a non-relational database such as CouchDB.
In this we can work with SQL query.
SQLite does not require a separate server process or system to operate.
The SQLite library accesses its storage files directly.
SQLite supports most of the query language features found in the SQL92 (SQL2) standard.

Cluster Class

Class clusters are a design pattern that the Foundation framework makes extensive use of. Class clusters group a number of private concrete subclasses under a public abstract superclass. The grouping of classes in this way simplifies the publicly visible architecture of an object-oriented framework without reducing its functional richness.

#import and @class filename

#import brings the entire header file in question into the current file; any files that THAT file
#imports are also included. @class, on the other hand (when used on a line by itself with some class names), just tells the compiler "Hey, you're going to see a new token soon; it's a class, so treat it that way).

KVC

Please read from below link.

Click here

Responder Chain and First Responder

A ResponderChain is a hierarchy of objects that have the opportunity to respond to events received.

The first object in the ResponderChain is called the FirstResponder.

Plist

Property lists organise data into named values and lists of values using several object types. These types give you the means to produce data that is meaningfully structured, transportable, storable, and accessible, but still as efficient as possible. Property lists are frequently used by applications running on both Mac OS X and iOS. The property-list programming interfaces for Cocoa and Core Foundation allow you to convert hierarchically structured combinations of these basic types of objects to and from standard XML. You can save the XML data to disk and later use it to reconstruct the original objects.

The user defaults system, which you programmatically access through the NSUserDefaults class, uses property lists to store objects representing user preferences. This limitation would seem to exclude many kinds of objects, such as NSColor and NSFont objects, from the user default system. But if objects conform to the NSCoding protocol they can be archived to NSData objects, which are property list–compatible objects

Notification and Observers

A notification is a message sent to one or more observing objects to inform them of an event in a program. The notification mechanism of Cocoa follows a broadcast model. It is a way for an object that initiates or handles a program event to communicate with any number of objects that want to know about that event. These recipients of the notification, known as observers, can adjust their own appearance, behaviour, and state in response to the event. The object sending (or posting) the notification doesn’t have to know what those observers are. Notification is thus a powerful mechanism for attaining coordination and cohesion in a program. It reduces the need for strong dependencies between objects in a program (such dependencies would reduce the reusability of those objects). Many classes of the Foundation, AppKit, and other Objective-C frameworks define notifications that your program can register to observe.

The centrepiece of the notification mechanism is a per-process singleton object known as the notification centre (NSNotificationCenter). When an object posts a notification, it goes to the notification centre, which acts as a kind of clearing house and broadcast centre for notifications. Objects that need to know about an event elsewhere in the application register with the notification centre to let it know they want to be notified when that event happens. Although the notification centre delivers a notification to its observers synchronously, you can post notifications asynchronously using a notification queue (NSNotificationQueue).

Application lifecycle

Chronology of an application: When the process is started, it runs the NSApplicationMain function, which creates an instance of NSApplication. The application object reads the main nib file and unarchives the objects inside. The objects are all sent the message awakeFromNib. Then the application object checks for events.
This lifecycle of a typical cocoa application is depicted in the below diagram.










Threadsafe

When it comes to threaded applications, nothing causes more fear or confusion than the issue of handling signals. Signals are a low-level BSD mechanism that can be used to deliver information to a process or manipulate it in some way. Some programs use signals to detect certain events, such as the death of a child process. The system uses signals to terminate runaway processes and communicate other types of information.

The problem with signals is not what they do, but their behavior when your application has multiple threads. In a single-threaded application, all signal handlers run on the main thread. In a multithreaded application, signals that are not tied to a specific hardware error (such as an illegal instruction) are delivered to whichever thread happens to be running at the time. If multiple threads are running simultaneously, the signal is delivered to whichever one the system happens to pick. In other words, signals can be delivered to any thread of your application.

The first rule for implementing signal handlers in applications is to avoid assumptions about which thread is handling the signal. If a specific thread wants to handle a given signal, you need to work out some way of notifying that thread when the signal arrives. You cannot just assume that installation of a signal handler from that thread will result in the signal being delivered to the same thread.

Threads and how to use

Use this class when you want to have an Objective-C method run in its own thread of execution. Threads are especially useful when you need to perform a lengthy task, but don’t want it to block the execution of the rest of the application. In particular, you can use threads to avoid blocking the main thread of the application, which handles user interface and event-related actions. Threads can also be used to divide a large job into several smaller jobs, which can lead to performance increases on multi-core computers.
Two ways to create threads…
·         detachNewThreadSelector:toTarget:withObject:
·         Create instances of NSThread and start them at a later time using the “start” method.
NSThread is not as capable as Java’s Thread class, it lacks
·         Built-in communication system.
·         An equivalent of “join()”

What it does “@synthesize boxDescription=boxName;”?

Here you can use boxName or self.boxName. We cant use boxDescription.

@property, @synthesize, @dyanamic

·       Properties are a feature in Objective-C that allow us to automatically generate accessors
·       The @synthesize directive automatically generates the setters and getters for us, so all we have to implement for this class is the dealloc method.
·       @synthesize will generate getter and setter methods for your property. @dynamic just tells the compiler that the getter and setter methods are implemented not by the class itself but somewhere else (like the superclass)
·       Uses for @dynamic are e.g. with subclasses of NSManagedObject (CoreData) or when you want to create an outlet for a property defined by a superclass that was not defined as an outlet:

Memory Leak

If RetainingAndReleasing are not properly used then RetainCount for AnObject doesn’t reach 0. It doesn’t crash the application.

autorelease vs release

Autorelase: By sending an object an autorelease message, it is added to the local AutoReleasePool, and you no longer have to worry about it, because when the AutoReleasePool is destroyed (as happens in the course of event processing by the system) the object will receive a release message, its RetainCount will be decremented, and the GarbageCollection system will destroy the object if the RetainCount is zero.
Release: retain count is decremented at this point.

NSAutoReleasePool : release vs drain

Strictly speaking, from the big picture perspective drain is not equivalent to release:
In a reference-counted environment, drain does perform the same operations as release, so the two are in that sense equivalent. To emphasise, this means you do not leak a pool if you use drain rather than release.
In a garbage-collected environment, release is a no-op. Thus it has no effect. drain, on the other hand, contains a hint to the collector that it should "collect if needed". Thus in a garbage-collected environment, using drain helps the system balance collection sweeps.

release vs pool drain

“release” frees a memory. “drain” releases the NSAutoreleasePool itself.

Alloc vs New

“alloc” creates a new memory location but doesn’t initializes it as compared to “new”.

Saturday, December 26, 2015

Why category is better than inheritance?

If category is used, you can use same class, no need to remember a new class-name. Category created on a base class is available on sub classes.

Foundation Kit

The Foundation framework defines a base layer of Objective-C classes. In addition to providing a set of useful primitive object classes, it introduces several paradigms that define functionality not covered by the Objective-C language. The Foundation framework is designed with these goals in mind:
·         Provide a small set of basic utility classes.
·         Make software development easier by introducing consistent conventions for things such as deallocation.
·         Support Unicode strings, object persistence, and object distribution.
·         Provide a level of OS independence, to enhance portability.

Application Kit/App kit

The Application Kit is a framework containing all the objects you need to implement your graphical, event-driven user interface: windows, panels, buttons, menus, scrollers, and text fields. The Application Kit handles all the details for you as it efficiently draws on the screen, communicates with hardware devices and screen buffers, clears areas of the screen before drawing, and clips views.
You also have the choice at which level you use the Application Kit:
·         Use Interface Builder to create connections from user interface objects to your application objects.
·         Control the user interface programmatically, which requires more familiarity with AppKit classes and protocols.
·         Implement your own objects by subclassing NSView or other classes.

Objective-C vs C/C++

·       The Objective-C class allows a method and a variable with the exact same name. In C++, they must be different.
·       Objective-C does not have a constructor or destructor. Instead it has init and dealloc methods, which must be called explicitly.
·       Objective-C uses + and - to differentiate between class method (known as factory method in Java) and instance methods, C++ uses static to specify a factory method.
·       Multiple inheritance is not allowed in Obj-C, however we can use protocol to some extent.
·       Obj-C has runtime binding leading to dynamic linking.
·       Obj-C has categories.
·       Objective-C has a work-around for method overloading, but none for operator overloading.
·       Objective-C also does not allow stack based objects. Each object must be a pointer to a block of memory.
·       In Objective-C the message overloading is faked by naming the parameters. C++ actually does the same thing but the compiler does the name mangling for us. In Objective-C, we have to mangle the names manually. If you go in deep you will see a complete method names are as : `addA:withB:` which is a selector and `:` is used for parameter.
·       One of C++'s advantages and disadvantages is automatic type coercion.
·       Another feature C++ has that is missing in Objective-C is references. Because pointers can be used wherever a reference is used, there isn't much need for references in general.
·       Templates are another feature that C++ has that Objective-C doesn't. Templates are needed because C++ has strong typing and static binding that prevent generic classes, such as List and Array.

Explain: Objective-C

Objective-C is a very dynamic language. Its dynamism frees a program from compile-time and link-time constraints and shifts much of the responsibility for symbol resolution to runtime, when the user is in control. Objective-C is more dynamic than other programming languages because its dynamism springs from three sources:

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

Garbage collection(GC) in iOS

iOS has no method of Garbage Collection. Even so, Garbage Collection is entirely unnecessary (for all practical purposes) when ARC is used. ARC works its magic at compile time to do the reference counting for you thereby making it unnecessary (and actually non-allowed) to use any other sort of memory management.
Edit:
To clarify, OS X does currently support garbage collection, but it is deprecated (unbeknown to me until a few minutes ago) as of OS X Mountain Lion. iOS never has and never will support garbage collection. Any advantages of garbage collection are moot when compared to those of ARC, and Apple has made the move to (forcefully) nudge us in the right direction.

Consider we are implementing our own thread with lot of autoreleased object. Is it mandatory to use autorelease pool on this scenario if yes/no why?

YES

When will be the autorelease object released?

Once the pool receives drain message.

What is the configuration file name in iOS explain in brief ? (Or) What is plist file and explain about it is usage?

A property list is a representation of a hierarchy of objects that can be stored in the file system and reconstituted later. Property lists give applications a lightweight and portable way to store small amounts of data. They are hierarchies of data made from specific types of objects—they are, in effect, an object graph. Property lists are easy to create programmatically and are even easier to serialize into a representation that is persistent. Applications can later read the static representation back into memory and recreate the original hierarchy of objects. Both Cocoa Foundation and Core Foundation have APIs related to property list serialization and deserialization.

Property List Types and Objects

Property lists consist only of certain types of data: dictionaries, arrays, strings, numbers (integer and float), dates, binary data, and Boolean values. Dictionaries and arrays are special types because they are collections; they can contain one or multiple data types, including other dictionaries and arrays. This hierarchical nesting of objects creates a graph of objects. The abstract data types have corresponding Foundation classes, Core Foundation types, and XML elements for collection objects and value objects.

What is Dynamic typing?

A variable is dynamically typed when the type of the object it points to is not checked at compile time. Objective-C uses the id data type to represent a variable that is an object without specifying what sort of object it is. This is referred to as dynamic typing.

Dynamic typing contrasts with static typing, in which the system explicitly identifies the class to which an object belongs at compile time. Static type checking at compile time may ensure stricter data integrity, but in exchange for that integrity, dynamic typing gives your program much greater flexibility. And through object introspection (for example, asking a dynamically typed, anonymous object what its class is), you can still verify the type of an object at runtime and thus validate its suitability for a particular operation.

What is run loop in iOS?

Run loops are part of the fundamental infrastructure associated with threads. A run loop is an event processing loop that you use to schedule work and coordinate the receipt of incoming events. The purpose of a run loop is to keep your thread busy when there is work to do and put your thread to sleep when there is none.

Run loop management is not entirely automatic. You must still design your thread’s code to start the run loop at appropriate times and respond to incoming events. Both Cocoa and Core Foundation provide run loop objects to help you configure and manage your thread’s run loop. Your application does not need to create these objects explicitly; each thread, including the application’s main thread, has an associated run loop object. Only secondary threads need to run their run loop explicitly, however. In both Carbon and Cocoa applications, the main thread automatically sets up and runs its run loop as part of the general application startup process.

Atomic vs Nonatomic @property(atomic, retain)……., @property(retain)…….,@property(nonatomic, retain)…….

Atomic is the default behaviour, so first and second are same.
Assuming that you are @synthesizing the method implementations, atomic vs. non-atomic changes the generated code. If you are writing your own setter/getters, atomic/nonatomic/retain/assign/copy are merely advisory.
With atomic, the synthesized setter/getter will ensure that a whole value is always returned from the getter or set by the setter, regardless of setter activity on any other thread. That is, if thread A is in the middle of the getter while thread B calls the setter, an actual viable value -- an autoreleased object, most likely -- will be returned to the caller in A.

In nonatomic, no such guarantees are made. Thus, nonatomic is considerably faster than atomic.
What atomic does not do is make any guarantees about thread safety. If thread A is calling the getter simultaneously with thread B and C calling the setter with different values, thread A may get any one of the three values returned -- the one prior to any setters being called or either of the values passed into the setters in B and C. Likewise, the object may end up with the value from B or C, no way to tell.
Ensuring data integrity -- one of the primary challenges of multi-threaded programming -- is achieved by other means.

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 centre. The notification centre 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 centre has broadcast the notification to all observers. For asynchronous behaviour, you can put the notification in a notification queue; control returns immediately to the posting object and the notification centre broadcasts the notification when it reaches the top of the queue.Regular notifications - that is, those broadcast by the notification centre - are intraprocess only. If you want to broadcast notifications to other processes, you can use the distributed notification centre and its related API.

Difference: 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 behaviour added by categories is a compile-time artefact, 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.

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.Refer: Singleton Pattern

Example:
Making singleton of MyClass

+ (instancetype)sharedInstance
{
    static MyClass *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[MyClass alloc] init];
        // Do any other initialisation stuff here
    });
    return sharedInstance;
}


//In Swift
class SomeManager {
    static let sharedInstance = SomeManager()
}

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.

Example:
Let's assume an object A calls an object B to perform an action. Once the action is complete, object A should know that B has completed the task and take necessary action. This is achieved with the help of delegates.

The key concepts in the above example are −
A is a delegate object of B.
B will have a reference of A.
A will implement the delegate methods of B.
B will notify A through the delegate methods.

What is categories in iOS?

We use categories to define additional methods of an existing class—even one whose source code is unavailable to you—without subclassing. You typically use a category to add methods to an existing class, such as one defined in the Cocoa frameworks. The added methods are inherited by subclasses and are indistinguishable at runtime from the original methods of the class. You can also use categories of your own classes to:

Distribute the implementation of your own classes into separate source files—for example, you could group the methods of a large class into several categories and put each category in a different file.
Declare private methods.
You add methods to a class by declaring them in an interface file under a category name and defining them in an implementation file under the same name. The category name indicates that the methods are an extension to a class declared elsewhere, not a new class.

What is Wildcard App IDs?

A wildcard app ID allows you to use an app ID to match multiple apps; wildcard app IDs are useful when you first start developing new apps because you don’t need to create a separate app ID for each app. However, wildcard app IDs can’t be used to provision an app that uses APNS, In App Purchase, or Game Center.

A wildcard app ID omits some or all of the bundle ID in the search string and replaces that portion with an asterisk character (*). The asterisk must always appear as the last character in the bundle search string.

When you use a wildcard app ID, characters preceding the asterisk (if any) must match the characters in the bundle ID, exactly as they would for an explicit app ID. The asterisk matches all remaining characters in the bundle ID. Further, the asterisk must match at least one character in the bundle ID. This table shows an example search string and how it matches some bundle IDs but not others.

If an app id uses an * as the bundle ID, then the search string matches any bundle ID.

MVC (Model View Controller)

It is useful to divide the complex task of computer application design into domains in order to simplify the process. Object oriented approaches are modular in philosophy, so the Model View Controller design pattern is a popular way to make logical divisions among class responsibilities.
Each object oriented programming environment/language has a slightly different definition/convention of MVC.

The main advantage of adopting a design pattern like MVC is that it allows the code in each unit to be decoupled from the others, making it more robust and immune to changes in other code.
Within the scope of Cocoa, MVC is an extremely important pattern. The major enhancements that Apple have made to Cocoa, namely Bindings and Core Data, are manifestly based on the MVC pattern.

Model: A Model object:
Is usually a simple subclass of NSObject (or an instance of NSManagedObject for CoreData)
Has a set of instance variables in which to store its data
Has a series of accessor methods for those ivars
Has one or more init: methods to return new instances to other classes
Has a dealloc method
May have custom methods to manipulate the model objects internal data
Is frequently reusable

View: A View object:
Is some subclass of NSView
Contains a drawRect: method which is the basis of all drawing
Is rarely subclassed or modified
Makes extensive use of delegates for customisation
Is generally reusable

Controller: A Controller object:
Mediates between model and view
Is usually a subclass of NSObject
Contains the outlets and actions for IB
Contains ivars and collections to own and hold model objects
Has methods for manipulating and composing model objects
Contains the main awakeFromNib method
Is instantiated in the nib file/s
Contains the business logic of the program
Is rarely reusable

What is Automatic Reference Counting (ARC) ?

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.

Implement methods: retain, release, autorelease.

-(id)retain
{
NSIncrementExtraRefCount(self);
return self;
}

-(void)release
{
if(NSDecrementExtraRefCountWasZero(self))
{
NSDeallocateObject(self);
}
}

-(id)autorelease
{
// Add the object to the autorelease pool
[NSAutoreleasePool addObject:self];
return self;
}

Implement your own synthesized methods for the property NSString *title.

You would want to implement the getter and setter for the title object. Something like this: view source print?

– (NSString*) title // Getter method
{
return title;
}

– (void) setTitle: (NSString*) newTitle //Setter method
{
if (newTitle != title)
{
[title release];
title = [newTitle retain]; // Or copy, depending on your needs.
}
}

Explain the difference between NSOperationQueue concurrent and non-concurrent.

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 happens when the given code executes? Ball *ball = [[[[Ball alloc] init] autorelease] autorelease];

It will crash because itʼs added twice to the autorelease pool and when it it dequeued the autorelease pool calls release more than once.

What is dynamic?

You use the @dynamic keyword to tell the compiler that you will fulfil the API contract implied by a property either by providing method implementations directly or at runtime using other mechanisms such as dynamic loading of code or dynamic method resolution. It suppresses the warnings that the compiler would otherwise generate if it can’t find suitable implementations. You should use it only if you know that the methods will be available at runtime.

What is sandbox?

For security reasons, iOS places each app (including its preferences and data) in a sandbox at install time. A sandbox is a set of fine-grained controls that limit the app’s access to files, preferences, network resources, hardware, and so on. As part of the sandboxing process, the system installs each app in its own sandbox directory, which acts as the home for the app and its data.

To help apps organise their data, each sandbox directory contains several well-known subdirectories for placing files. Above Figure shows the basic layout of a sandbox directory.

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.

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

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

If I call performSelector:withObject:afterDelay: – is the object retained?

Yes, the object is retained. It creates a timer that calls a selector on the current threads run loop. It may not be 100% precise time-wise as it attempts to dequeue the message from
the run loop and perform the selector.

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


  • For Voice over Internet Protocol (VoIP) notifications, the maximum payload size is 5 KB (5120 bytes).
  • For all other remote notifications, the maximum payload size is 4 KB (4096 bytes).

Multitasking support is available from which version?

iOS 4.0.

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.How can you do retain without @property?

if (_variable != object)
{
    [_variable release];
    _variable = nil;
    _variable = [object retain];
}

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.

Explain the steps involved in submitting the App to App-Store.

Apple provides the tools you need to develop, test, and submit your iOS app to the App Store. To run an app on a device, the device needs to be provisioned for development, and later provisioned for testing. You also need to provide information about your app that the App Store displays to customers and upload screenshots. Then you submit the app to Apple for approval. After the app is approved, you set a date the app should appear in the App Store as well as its price. Finally, you use Apple’s tools to monitor the sales of the app, customer reviews, and crash reports. Then you repeat the entire process again to submit updates to your app.


Explain how the push notification works.

https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/index.html#//apple_ref/doc/uid/TP40008194-CH3-SW1



Apple Push Notification service (APNs) propagates push notifications to devices having applications registered to receive those notifications. Each device establishes an accredited and encrypted IP connection with the service and receives notifications over this persistent connection. Providers connect with APNs through a persistent and secure channel while monitoring incoming data intended for their client applications. When new data for an application arrives, the provider prepares and sends a notification through the channel to APNs, which pushes the notification to the target device.


App states or Application states

  1. Non-running - The app is not running. 
  2. Inactive - The app is running in the foreground, but not receiving events. An iOS app can be placed into an inactive state, for example, when a call or SMS message is received. 
  3. Active - The app is running in the foreground, and receiving events. 
  4. Background - The app is running in the background, and executing code. 
  5. Suspended - The app is in the background, but no code is being executed.

Outline the class hierarchy for a UIButton until NSObject.

UIButton inherits from UIControl, UIControl inherits from UIView, UIView inherits from UIResponder, UIResponder inherits from the root class NSObject.

Is a delegate retained?

No, the delegate is never retained

Only for CAAnimation delegate retained
This is one of the rare exceptions to memory management rules.

Explanation:
It's a memory management thing.

Objective-C works with reference counts to keep the memory clean. This does mean that it can't detect cyclic relationships.

Example:

Object A owns object B. Object B is retained by object A.
Object B has a delegate that is object A. Object A is retained by object B.
Object C owns object A. Object A is retained by object C.
Object A now has a retainCount of 2, and object B has a retainCount of 1
Object C gets freed, and releases object A
Object A and B now have a retainCount of 1, because they own each other. The system will not free them, because the retainCount is still 1 (still owned by another object)
Memory leak!

What is retain counts?

Retain counts are the way in which memory is managed in Objective-C. 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 some stage in the future. If an objectʼs retain count is reduced to 0, it is deallocated.


Whats the difference between NSArray and NSMutableArray?

NSArrayʼs contents can not be modified once itʼs been created whereas a NSMutableArray can be modified as needed, i.e items can be added/removed from it.

Whats a struct?

A struct is a special C data type that encapsulates other pieces of data into a single cohesive unit. Like an object, but built into C.

Whats fast enumeration?

Fast enumeration is a language feature that allows you to enumerate over the contents of a collection. (Your code will also run faster because the internal implementation reduces message send overhead and increases pipelining potential.)

What is App Bundle?

When you build your iOS app, Xcode packages it as a bundle. A bundle is a directory in the file system that groups related resources together in one place. An iOS app bundle contains the app executable file and supporting resource files such as app icons, image files, and localized content.

How would you create your own custom view?

By Subclassing the UIView class.