Download as pdf or txt
Download as pdf or txt
You are on page 1of 122

iOS Interview Questions and Answers

BY: SANDEEP REDDY CHALLA


1-How would you create your own custom view?
By Subclassing the UIView class.
2-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.)

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

4-What are mutable and immutable types in Objective C?


Mutable means you can change its contents later but when you mark any object
immutable, it means once they are initialized, their values cannot be changed. For
example, NSArray, NSString values cannot be changed after initialized.
5-Explain 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.
6-Whats the difference between frame and bounds?
The frame of a view is the rectangle, expressed as a location (x,y) and size
(width,height) relative to the superview it is contained within. The bounds of
a view is the rectangle, expressed as a location (x,y) and size (width,height)
relative to its own coordinate system (0,0).

7-Is a delegate retained?


No, the delegate is never retained! Ever!
8-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
9- What is dynamic?
You use the @dynamic keyword to tell the compiler that you will fulfill 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
10-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.
11-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.)
12-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).

13-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.
14-Is the delegate for a CAAnimation retained?
Yes it is!! This is one of the rare exceptions to memory management rules.
15-What happens when the following 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.
16-Implement your own synthesized methods for the property NSString
*title.
Well 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. }
}
17-Implement the following 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
}
18-What are the App states. Explain them?

• Not running State: The app has not been launched or was running but
was terminated by the system.
• Inactive state: The app is running in the foreground but is currently not
receiving events. (It may be executing other code though.) An app
usually stays in this state only briefly as it transitions to a different state.
The only time it stays inactive for any period of time is when the user
locks the screen or the system prompts the user to respond to some
event, such as an incoming phone call or SMS message.
• Active state: The app is running in the foreground and is receiving
events. This is the normal mode for foreground apps.

• Background state: The app is in the background and executing code. Most
apps enter this state briefly on their way to being suspended. However, an
app that requests extra execution time may remain in this state for a
period of time. In addition, an app being launched directly into the
background enters this state instead of the inactive state. For
information about how to execute code while in the background, see
“Background Execution and Multitasking.”
• Suspended state:The app is in the background but is not executing code.
The system moves apps to this state automatically and does not notify

them before doing so. While suspended, an app remains in memory but does not
execute any code. When a low-memory condition occurs, the system may purge
suspended apps without notice to make more space for the foreground app.
19-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.
20-Multitasking support is available from which version?
iOS 4 and above supports multi-tasking and allows apps to remain in the
background until they are launched again or until they are terminated.

21-What is the difference 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];
}

22-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
23-What is 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.
24-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
thewindowWillResize: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
theapplicationDidFinishLaunching: message. The delegate is then able to
perform additional tasks if it wants.
25-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 includeNSFileManager, 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.
26-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 NSXMLParserobject) 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 4-3). Thus delegation makes it possible
to modify or extend the behavior of another object without the need for
subclassing.Refer: delegate pattern
27-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.

28.iOS life cycle.

CORE OS - The kernel in iOS is based on a variant of the same basic Mach
kernel that is found in Mac OS X.
CORE OS and CORE SERVICES LAYERS - These interfaces are mostly C-
based and include technologies such as Core Foundation, CFNetwork, SQLite,
and access to POSIX threads and UNIX sockets among others.
MEDIA LAYER – The Media layer contains the fundamental technologies
used to support 2D and 3D drawing, audio, and video. This layer includes the
C-based technologies OpenGL ES, Quartz, and Core Audio. It also contains
Core Animation, which is an advanced Objective-C based animation engine.

COCOA TOUCH
In the Cocoa Touch layer, most of the technologies use Objective-C. The
frameworks at these layers provide the fundamental infrastructure used by your
application. For example, the Foundation framework provides object-oriented
support for collections, file management, network operations, and more. The
UIKit framework provides the visual infrastructure for your application,
including classes for windows, views, controls, and the controllers that manage
those objects. Other frameworks at this level give you access to the user’s
contact and photo information and to the accelerometers and other hardware
features of the device.

29. iOS SOFTWARE LIFE CYCLE IOS 4.0 LATER


30. iOS LIFE CYCLE TILL IOS 3.0

31-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.
32-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.
33-What is posing in iOS?
Objective-C permits a class to entirely replace another class within an
application. The replacing class is said to “pose as” the target class. All
messages sent to the target class are then instead received by the posing
class. There are some restrictions on which classes can pose:
• A class may only pose as one of its direct or indirect superclasses
• The posing class must not define any new instance variables which are
absent from the target class (though it may define or override methods). •
No messages must have been sent to the target class prior to the posing.
Posing, similarly to categories, allows globally augmenting existing classes.
Posing permits two features absent from categories:
• A posing class can call overridden methods through super,
thus incorporating the implementation of the target class.

• A posing class can override methods defined in categories.

34-What is atomic and nonatomic? Which one is safer? Which


one is default?
You can use this attribute to specify that accessor methods are not
atomic. (There is no keyword to denote atomic.)nonatomic
Specifies that accessors are nonatomic. By default, accessors are atomic.
Properties are atomic by default so that synthesized accessors provide
robust access to properties in a multithreaded environment—that is, the
value returned from the getter or set via the setter is always fully
retrieved or set regardless of what other threads are executing
concurrently. 

If you specify strong, copy, or retain and do not specifynonatomic, then
in
a reference-counted environment, a synthesized get accessor for an object 


property uses a lock and retains and autoreleases the returned value—
the implementation will be similar to the following:


[_internal lock]; // lock using an object-level lock


id result = [[value retain] autorelease]; 


[_internal unlock];


return result;


If you specify nonatomic, a synthesized accessor for an object


property simply returns the value directly.

35-Where can you test Apple iPhone apps if you don’t have
the device?
iOS Simulator can be used to test mobile applications. Xcode tool that
comes along with iOS SDK includes Xcode IDE as well as the iOS
Simulator. Xcode also includes all required tools and frameworks for
building iOS apps. However, it is strongly recommended to test the
app on the real device before publishing it.


36-Which JSON framework is supported by iOS?


SBJson framework is supported by iOS. It is a JSON parser and
generator for Objective-C. SBJson provides flexible APIs and additional
control that makes JSON handling easier.

37-What are the tools required to develop iOS applications?


iOS development requires Intel-based Macintosh computer Xcode IDE and
iOS SDK.

38- Name the framework that is used to construct application’s


user interface for iOS.
The UIKit framework is used to develop application’s user interface for iOS.
UIKit framework provides event handling, drawing model, windows, views,
and controls specifically designed for a touch screen interface.

39-Name the application thread from where UIKit classes should be used?
UIKit classes should be used only from an application’s main thread. Note:
The derived classes of UIResponder and the classes which manipulate
application’s user interface should be used from application’s main thread.
40- Which API is used to write test scripts that help in exercising
the application’s user interface elements?
UI Automation API is used to automate test procedures. Tests scripts are written
in JavaScript to the UI Automation API. This in turn simulates user interaction
with the application and returns log information to the host computer.
41-Why an app on iOS device behaves differently when running
in foreground than in background?
An application behaves differently when running in foreground than
in background because of the limitation of resources on iOS devices.
42- How can an operating system improve battery life while running
an app?
An app is notified whenever the operating system moves the apps between
foreground and background. The operating system improves battery life while
it bounds what your app can do in the background. This also improves the user
experience with foreground app.
43-Which framework delivers event to custom object when app is
in foreground?
The UIKit infrastructure takes care of delivering events to custom objects.
As an app developer, you have to override methods in the appropriate
objects to process those events.
44-When an app is said to be in not running state?
An app is said to be in ‘not running’ state when:
- it is not launched.
- it gets terminated by the system during running.
45-Assume that your app is running in the foreground but is currently
not receiving events. In which sate it would be in?
An app will be in InActive state if it is running in the foreground but is
currently not receiving events. An app stays in InActive state only briefly as
it transitions to a different state.
46- Give example scenarios when an application goes into InActive state?
An app can get into InActive state when the user locks the screen or the system
prompts the user to respond to some event e.g. SMS message, incoming call
etc.
47-When an app is said to be in active state?
An app is said to be in active state when it is running in foreground and is
receiving events.
48-Name the app sate which it reaches briefly on its way to being
suspended
An app enters background state briefly on its way to being suspended.
49- Assume that an app is not in foreground but is still executing code. In
which state will it be in?
Background state.
50-An app is loaded into memory but is not executing any code. In which
state will it be in?
An app is said to be in suspended state when it is still in memory but is not
executing any code.
51-Assume that system is running low on memory. What can system do for
suspended apps?
In case system is running low on memory, the system may purge suspended
apps without notice.
52- How can you respond to state transitions on your app?
On state transitions can be responded to state changes in an appropriate way by
calling corresponding methods on app’s delegate object.
For example: applicationDidBecomeActive method can be used to prepare to
run as the foreground app.
applicationDidEnterBackground method can be used to execute some code
when app is running in the background and may be suspended at any time.
applicationWillEnterForeground method can be used to execute some code
when your app is moving out of the background
applicationWillTerminate method is called when your app is being terminated.
53-List down app’s state transitions when it gets launched.]
Before the launch of an app, it is said to be in not running state.
When an app is launched, it moves to the active or background state,
after transitioning briefly through the inactive state.
54-Who calls the main function of you app during the app launch cycle?
During app launching, the system creates a main thread for the app and calls
the app’s main function on that main thread. The Xcode project’s default main
function hands over control to the UIKit framework, which takes care of
initializing the app before it is run.
55-What is the use of controller object UIApplication?
Controller object UIApplication is used without subclassing to manage
the application event loop.
It coordinates other high-level app behaviors.
It works along with the app delegate object which contains app-level logic.
56-Which object is create by UIApplicationMain function at app
launch time?
The app delegate object is created by UIApplicationMain function at app
launch time. The app delegate object’s main job is to handle state
transitions within the app.
57- How is the app delegate is declared by Xcode project templates?
App delegate is declared as a subclass of UIResponder by Xcode
project templates.
58-What happens if IApplication object does not handle an event?
In such case the event will be dispatched to your app delegate for processing.
59- Which app specific objects store the app’s content?

Data model objects are app specific objects and store app’s content. Apps can
also use document objects to manage some or all of their data model objects.
60-Are document objects required for an application? What does
they offer?
Document objects are not required but are very useful in grouping data
that belongs in a single file or file package.
61- Which object manage the presentation of app’s content on the screen?
View controller objects takes care of the presentation of app’s content on the
screen. A view controller is used to manage a single view along with the
collection of subviews. It makes its views visible by installing them in the
app’s window.
62- Which is the super class of all view controller objects?
UIViewController class. The functionality for loading views, presenting them,
rotating them in response to device rotations, and several other standard
system behaviors are provided by UIViewController class.
63-What is the purpose of UIWindow object?
The presentation of one or more views on a screen is coordinated by
UIWindow object.
64-How do you change the content of your app in order to change the
views displayed in the corresponding window?
To change the content of your app, you use a view controller to change the
views displayed in the corresponding window. Remember, window itself
is never replaced.
65-Define view object.
Views along with controls are used to provide visual representation of the
app content. View is an object that draws content in a designated rectangular
area and it responds to events within that area.
66-Apart from incorporating views and controls, what else an app
can incorporate?
Apart from incorporating views and controls, an app can also incorporate
Core Animation layers into its view and control hierarchies.
67- What are layer objects and what do they represent?
Layer objects are data objects which represent visual content. Layer objects are
used by views to render their content. Custom layer objects can also be added
to the interface to implement complex animations and other types of
sophisticated visual effects.
68-What is App Bundle?
When you build your iOS app, Xcode packages it as a bundle. Appbundle 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.
69-Define property?
It is used to access instance variables outside of class.
70-Why synthesized is used?
After declaring property we will have to tell compiler instantly by using
synthesize directive. This tells the compiler to generate setter and getter
methods.
71-What is retaining?
It is reference count for an object.
72- What is webservice?
To get data in form of xml ,by using this we can get data from a server.
73-What is parsing?

To get data from web service we use parsing.


74-which xml parser we use on iphone?
“NSXML” Parser.
75-Which type of parse does iphone support?

“SAX” parser.
76-.Name those classes used to establish connection b/w application to
webserver?
(a)NSURL (b)NSURL REQUEST (c)NSURL CONNECTION.
77-Tell the difference between DOM and SAX Parser?
(a)Dom is “documents based parser”. b)SAX is a event driven parser
78-Name three method of NSXML parser.

(1)did start element (2)did end element (3)found character.


79-Tell methods used in NSURLConnection
(1)Connection did receive Response (2)Connection did recevice Datat
(3)Connection fail with error (4)Connection did finish loading.
80-.What is json-parser?
JSON(Java script object notation)is a parser used to get data from web Server.
81-.By default which things are in the application?
iPhone applications by default have 3 things

1.main: entry point of application.
2.Appdelegate: perform basic application and functionality.
3.Window: provide uiinterface.
82-Tell me about tab bar controller?
It is used to display the data on the view.
83-Which are the protocols used in table view?
Table view contain two delegate protocols


(1) Uitable view data source


(2).Uitable view delegate.


ui view table view data source three method namely (1)No of sections.
(2)No of rows in sections.


(3)Cell for row index path row.


In ui table view delegate contain (1)Did select row at index path row
84-Name data base used in iphone?
(1)Sql lite (2)Plist 3)Xml (4)Core Data
85-Tell four frameworks used in iphone?
(1)Ui kit framework


(2)Map kit framework


(3)ADI kit framework


(4)Core data framework (5)core foundation framework


86-Tell me about single inheritance in objective-c?
Objective c subclass can derived from a single parent class.It is called “single
inheritance”.
87-Tell me about the MVC architecture?
M-model, V-view, C-controller


Main advantage of MVC architecture is to provide “reusability and security” by


separating the layer by using MVC architecture.

Model: it is a class model is interact with database.


Controller: controller is used for by getting the data from model and
controls the views.


Display the information in views. : View


88-What is the instance methods?
Instance methods are essentially code routines that perform tasks so instances
of clases we create methods to get and set the instance variables and to display
the current values of these variables.
Declaration of instance method :


– (void)click me: (id)sender;


Void is return type which does not giving any thing here. Click me is
method name.


Id is data type which returns any type of object.


89-What is the class method?

Class methods work at the class level and are common to all instance of a class
these methods are specific to the class overall as opposed to working on
different instance data encapsulated in each class instance.


@interface class name :ns object


{


}


+(class name *)new alloc: -(int)total open


90-What is data encapsulation?
Data is contained within objects and is not accessible by any other than via
methods defined on the class is called data encapsulation.
91-What is accessor methods?
Accessor methods are methods belonging to a class that allow to get and set the
values of instance valuables contained within the class.
92-What is synthesized accessor methods?
Objective-c provides a mechanism that automates the creation of accessor
methods that are called synthesized accessor methods that are implemented
through use of the @property and @synthesized.
93-How to access the encapsulated data in objective-c?

(a)Data encapsulation encourages the use of methods to +get and set the
values of instance variables in a class.

(b)But the developer to want to directly access an instance variable
without having to go through an accessor method.
(c) In objective-c syntax for an instance variable is as follow [class
instance variable name]
94-What is dot notation?
Dot notation features introduced into version 2.0 of objective-c. Dot
notation involves accessing an instance variable by specifying a class
“instance” followed by a “dot” followed in turn by the name of instance
variable or property to be accessed.
95-Difference between shallow copy and deep copy?

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.
96-Difference between categories and extensions?
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) — it’s meant to be just that, an extension.

98-Can we use two tableview controllers on one view controller?


Yes, we can use two tableviews on the same view controllers and you can
differentiate between two by assigning them tags...or you can also check them
by comparing their memory addresses.
99-Swap the two variable values without taking third variable?

int x=10;
int y=5;
x=x+y;
NSLog(@”x==> %d”,x); y=x-y;
NSLog(@”Y Value==> %d”,y);
x=x-y;
NSLog(@”x Value==> %d”,x);
100-What is push notification?

Imagine, you are looking for a job. You go to software company daily and ask
sir “is there any job for me” and they keep on saying no. Your time and money
is wasted on each trip.(Pull Request mechanism)


So, one day owner says, if there is any suitable job for you, I will let you know. In
this mechanism, your time and money is not wasted. (Push Mechanism)
How it works?
This service is provided by Apple in which rather than pinging server after
specific interval for data which is also called pull mechanism, server will send
notification to your device that there is new piece of information for you.
Request is initiated by server not the device or client.
Flow of push notification
Your web server sends message (device token + payload) to Apple push
notification service (APNS) , then APNS routes this message to device whose
device token specified in notification.
101-What is polymorphism?
This is very famous question and every interviewer asks this. Few people say
polymorphism means multiple forms and they start giving example of draw
function which is right to some extent but interviewer is looking for more
detailed answer.
Ability of base class pointer to call function from derived class at runtime is
called polymorphism.

For example, there is super class human and there are two subclasses software
engineer and hardware engineer. Now super class human can hold reference to
any of subclass because software engineer is kind of human. Suppose there is
speak function in super class and every subclass has also speak function. So at
runtime, super class reference is pointing to whatever subclass, speak function
will be called of that class. I hope I am able to make you understand.
101-What is responder chain?
Suppose you have a hierarchy of views such like there is superview A which
have subview B and B has a subview C. Now you touch on inner most view C.
The system will send touch event to subview C for handling this event. If C
View does not want to handle this event, this event will be passed to its
superview B (next
responder). If B also does not want to handle this touch event it will pass on to
superview A. All the view which can respond to touch events are called
responder chain. A view can also pass its events to uiviewcontroller. If view
controller also does not want to respond to touch event, it is passed to
application object which discards this event.
102-Can we use one tableview with two different datasources? How you
will achieve this?
Yes. We can conditionally bind tableviews with two different data sources.
103-What is a protocol?
A protocol is a language feature in objective C which provides multiple
inheritance in a single inheritance language. Objective C supports two types of
protocols:
• Ad hoc protocols called informal protocol
• Compiler protocols called formal protocols
You must create your own autorelease pool as soon as the thread begins
executing; otherwise, your application will leak objects
104-Three occasions when you might use your own autorelease pools:

1. If you are writing a program that is not based on a UI framework, such as


a command-line tool. 


2. If you write a loop that creates many temporary objects.You may create
an autorelease pool inside the loop to dispose of those objects before the
next iteration. Using an autorelease pool in the loop helps to reduce the
maximum memory footprint of the application. 


3. If you spawn a secondary thread.

105- InApp purchase product type

1. Consumable products must be purchased each time the user needs that
item. For example, one-time services are commonly implemented as
consumable products.
2. Non-consumable products are purchased only once by a particular user.
Once a non-consumable product is purchased, it is provided to all devices
associated with that user’s iTunes account. Store Kit provides built-in
support to restore non-consumable products on multiple devices.
3. Auto-renewable subscriptions are delivered to all of a user’s devices in
the same way as non-consumable products. However, auto-renewable
subscriptions differ in other ways. When you create an auto-renewable
subscription in iTunes Connect, you choose the duration of the
subscription. The App Store automatically renews the subscription each
time its term expires. If the user chooses to not allow the subscription to
be renewed, the user’s access to the subscription is revoked after the
subscription expires. Your application is responsible for validating
whether
a subscription is currently active and can also receive an updated receipt
for the most recent transaction.
4. Free subscriptions are a way for you to put free subscription content in
Newsstand. Once a user signs up for a free subscription, the content is available
on all devices associated with the user’s Apple ID. Free subscriptions do not
expire and can only be offered in Newsstand-enabled apps

107-What is the navigation controller?


Navigation controller contains the stack of controllers every navigation
controller
must be having root view controller by default these controllers contain 2
method


(a) push view (b) pop view


By default navigation controller contain “table view”.


108- What is the split view controller?

This control is used for ipad application and it contain proper controllers by
default


split view controller contain root view controller and detail view controller.
109-Cocoa.
Cocoa is an application environment for both the Mac OS X operating system
and iOS. It consists of a suite of object-oriented software libraries, a runtime
system, and an integrated development environment. Carbon is an alternative
environment in Mac OS X, but it is a compatibility framework with procedural
programmatic interfaces intended to support existing Mac OS X code bases.
110- Frameworks that make Cocoa.
Appkit (Application Kit) Foundation
111- 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
112- 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 factory 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 got 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.


· 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.
113-Appilcation 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.


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


115-Dynamic and Static Typing.
Static typed languages are those in which type checking is done at
compile-time, whereas dynamic typed languages are those in which type
checking is done at run-time.
Objective-C is a dynamically-typed language, meaning that you don’t have to
tell the compiler what type of object you’re working with at compile time.
Declaring a type for a varible is merely a promise which can be broken at
runtime if the code leaves room for such a thing. You can declare your
variables as type id, which is suitable for any Objective-C object.
116-Selectors
In Objective-C, selector has two meanings. It can be used to refer simply to the
name of a method when it’s used in a source-code message to an object. It also,
though, refers to the unique identifier that replaces the name when the source
code is compiled. Compiled selectors are of type SEL. All methods with the
same name have the same selector. You can use a selector to invoke a method
on an object—this provides the basis for the implementation of the target-
action design pattern in Cocoa.
[friend performSelector:@selector(gossipAbout:) withObject:aNeighbor];
is equivalent to:


[friend gossipAbout:aNeighbor];
117-Class Introspection
· Determine whether an objective-C object is an instance of a class

[obj isMemberOfClass:someClass];


· Determine whether an objective-C object is an instance of a class or


its descendants


[obj isKindOfClass:someClass];

· The version of a class


[MyString version]


· Find the class of an Objective-C object


· Verify 2 Objective-C objects are of the same class



[obj1 class] == [obj2 class]
118- Proxy

As long as there aren’t any extra instance variables, any subclass can proxy
itself as its superclass with a single call. Each class that inherits from the
superclass, no matter where it comes from, will now inherit from the proxied
subclass. Calling a method in the superclass will actually call the method in
the subclass. For libraries where many objects inherit from a base class,
proxying the superclass can be all that is needed.
119- 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.
120-Formal Protocols
Formal Protocols allow us to define the interface for a set of methods, but
implementation is not done. Formal Protocols are useful when you are
using DistributedObjects, because they allow you to define a protocol for
communication between objects, so that the DO system doesn’t have to
constantly check whether or not a certain method is implemented by the
distant object.
121- Formal vs informal protocol.

In addition to formal protocols, you can also define an informal protocol


by grouping the methods in a category declaration:

@interface NSObject (MyProtocol)


//someMethod();
@end


Informal protocols are typically declared as categories of the NSObject class,


because that broadly associates the method names with any class that inherits
from NSObject. Because all classes inherit from the root class, the methods
aren’t restricted to any part of the inheritance hierarchy. (It is also possible to
declare an informal protocol as a category of another class to limit it to a
certain branch of the inheritance hierarchy, but there is little reason to do so.)
When used to declare a protocol, a category interface doesn’t have a
corresponding implementation. Instead, classes that implement the protocol
declare the methods again in their own interface files and define them along
with other methods in their implementation files.


An informal protocol bends the rules of category declarations to list a group of


methods but not associate them with any particular class or implementation.
Being informal, protocols declared in categories don’t receive much language
support. There’s no type checking at compile time nor a check at runtime to see
whether an object conforms to the protocol. To get these benefits, you must use
a formal protocol. An informal protocol may be useful when all the methods
are optional, such as for a delegate, but (in Mac OS X v10.5 and later) it is
typically better to use a formal protocol with optional methods.
122- Optional vs required
Protocol methods can be marked as optional using the @optional keyword.
Corresponding to the @optional modal keyword, there is a @required keyword
to formally denote the semantics of the default behavior. You can use
@optional and @required to partition your protocol into sections as you see fit.
If you do not specify any keyword, the default is @required.
@protocol MyProtocol @optional


-(void) optionalMethod; @required


-(void) requiredMethod; @end
123- Memory Management
If you alloc, retain, or copy/mutablecopy it, it’s your job to release it.
Otherwise it isn’t.
124-Copy vs assign vs retain

· Assign is for primitive values like BOOL, NSInteger or double. For objects
use retain or copy, depending on if you want to keep a reference to the
original object or make a copy of it.


· assign: In your setter method for the property, there is a simple assignment
of your instance variable to the new value, eg: (void)setString:
(NSString*)newString{
string = newString;
}

This can cause problems since Objective-C objects use reference counting,
and therefore by not retaining the object, there is a chance that the string could
be deallocated whilst you are still using it.


· retain: this retains the new value in your setter method. For example:


This is safer, since you explicitly state that you want to maintain a reference of
the object, and you must release it before it will be deallocated. (void)setString:
(NSString*)newString{
[newString retain];
[string release];
string = newString;
}


· copy: this makes a copy of the string in your setter method:


This is often used with strings, since making a copy of the original object
ensures that it is not changed whilst you are using it. (void)setString:
(NSString*)newString{
if(string!=newString){
[string release];
string = [newString copy];

}
}
125- alloc vs new
“alloc” creates a new memory location but doesn’t initializes it as compared
to “new”.
126- release vs pool drain
“release” frees a memory. “drain” releases the NSAutoreleasePool itself.
127- 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.
128-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.
129- Autorelease Pool
Autorelease pools provide a mechanism whereby you can send an object a
“deferred” release message. This is useful in situations where you want to
relinquish ownership of an object, but want to avoid the possibility of it being
deallocated immediately (such as when you return an object from a method).
Typically, you don’t need to create your own autorelease pools, but there
are some situations in which either you must or it is beneficial to do so.
130- How autorelease pool is managed.
Every time -autorelease is sent to an object, it is added to the inner-most
autorelease pool. When the pool is drained, it simply sends -release to all
the objects in the pool.
Autorelease pools are simply a convenience that allows you to defer sending
- release until “later”. That “later” can happen in several places, but the most
common in Cocoa GUI apps is at the end of the current run loop cycle.
131-Memory Leak
If RetainingAndReleasing are not properly used then RetainCount for
AnObject doesn’t reach 0. It doesn’t crash the application.
132- Event Loop
In a Cocoa application, user activities result in events. These might be mouse
clicks or drags, typing on the keyboard, choosing a menu item, and so on.
Other events can be generated automatically, for example a timer firing
periodically, or something coming in over the network. For each event, Cocoa
expects there to be an object or group of objects ready to handle that event
appropriately. The event loop is where such events are detected and routed off
to the appropriate place. Whenever Cocoa is not doing anything else, it is
sitting in the event loop waiting for an event to arrive. (In fact, Cocoa doesn’t
poll for events as suggested, but instead its main thread goes to sleep. When an
event arrives, the OS wakes up the thread and event processing resumes. This
is much more efficient than polling and allows other applications to run more
smoothly).
Each event is handled as an individual thing, then the event loop gets the next
event, and so on. If an event causes an update to be required, this is checked
at the end of the event and if needed, and window refreshes are carried out.
133-Differnce between boxName and self.boxName.
boxName: Accessing directly.


self. boxName: Accessing boxName through accessors. If property/synthesize


is not there it will throw error.
134-What it does “@synthesize boxDescription=boxName;” ?
Here you can use boxName or self.boxName. We cant use boxDescription.
135-Collection
In Cocoa and Cocoa Touch, a collection is a Foundation framework class
used for storing and managing groups of objects. Its primary role is to store
objects in the form of either an array, a dictionary, or a set.
136-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()”
137-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.
138-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, behavior, 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 centerpiece of the notification mechanism is a per-process singleton object
known as the notification center (NSNotificationCenter). When an object posts
a notification, it goes to the notification center, which acts as a kind of clearing
house and broadcast center for notifications. Objects that need to know about
an event elsewhere in the application register with the notification center to let
it know they want to be notified when that event happens. Although the
notification center delivers a notification to its observers synchronously, you
can post notifications asynchronously using a notification queue
(NSNotificationQueue).
139-Delegate vs Notification
· The concept of notification differs from delegation in that it allows a message to
be sent to more than one object. It is more like a broadcast rather than a straight
communication between two objects. It removes dependencies between the
sending and receiving object(s) by using a notification center to manage the
sending and receiving of notifications. The sender does not need to know if
there are any receivers registered with the notification center. There can be one,
many or even no receivers of the notification registered with the notification
center. Simply, Delegate is 1-to-1 object and Notification can be *-to-* objects.
· The other difference between notifications and delegates is that there is no
possibility for the receiver of a notification to return a value to the sender.
· Typical uses of notifications might be to allow different objects with an
application to be informed of an event such as a file download completing or a
user changing an application preference. The receiver of the notification might
then perform additional actions such as processing the downloaded file or
updating the display.
140-Plist
Property lists organize 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
141-Helper Objects
Helper Objects are used throughout Cocoa and CocoaTouch, and usually take
the form of a delegate or dataSource. They are commonly used to add
functionality to an existing class without having to subclass it.
142-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.
143-Differentiate Foundation vs Core Foundation

CoreFoundation is a general-purpose C framework whereas Foundation is a


general-purpose Objective-C framework. Both provide collection classes, run
loops, etc, and many of the Foundation classes are wrappers around the CF
equivalents. CF is mostly open-source , and Foundation is closed-source.

Core Foundation is the C-level API, which provides CFString, CFDictionary
and the like.Foundation is Objective-C, which provides NSString,
NSDictionary, etc. CoreFoundation is written in C while Foundation is written
in Objective-C. Foundation has a lot more classes CoreFoundation is the
common base of Foundation and Carbon.
144-Difference between coreData and Database
Database


Core Data


Primary function is storing and fetching data


Primary function is graph management (although reading and writing to disk is


an important supporting feature)


Operates on data stored on disk (or minimally and incrementally loaded)


Operates on objects stored in memory (although they can be lazily loaded from
disk)


Stores “dumb” data


Works with fully-fledged objects that self-manage a lot of their behavior and
can be subclassed and customized for further behaviors

Can be transactional, thread-safe, multi-user

Non-transactional, single threaded, single user (unless you create an entire
abstraction around Core Data which provides these things)


Can drop tables and edit data without loading into memory

Only operates in memory


Perpetually saved to disk (and often crash resilient)



Requires a save process


Can be slow to create millions of new rows


Can create millions of new objects in-memory very quickly (although saving
these objects will be slow)


Offers data constraints like “unique” keys


Leaves data constraints to the business logic side of the program
145- Core data vs sqlite.
Core data is an object graph management framework. It manages a potentially
very large graph of object instances, allowing an app to work with a graph that
would not entirely fit into memory by faulting objects in and out of memory as
necessary. Core Data also manages constraints on properties and relationships
and maintains reference integrity (e.g. keeping forward and backwards links
consistent when objects are added/removed to/from a relationship). Core Data
is thus an ideal framework for building the “model” component of an MVC
architecture.
To implement its graph management, Core Data happens to use sqlite as a disk
store. Itcould have been implemented using a different relational database or
even a non-relational database such as CouchDB. As others have pointed out,
Core Data can also use XML or a binary format or a user-written atomic format
as a backend (though these options require that the entire object graph fit into
memory).
146-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.
147-What is unnamed category.
A named category — @interface Foo(FooCategory) — is generally used to: i.
Extend an existing class by adding functionality.


ii. Declare a set of methods that might or might not be implemented by a


delegate.
Unnamed Categories has fallen out of favor now that @protocol has
been extended to support @optional methods.


A class extension — @interface Foo() — is designed to allow you to declare


additional private API — SPI or System Programming Interface — that is used
to implement the class innards. This typically appears at the top of the .m file.
Any methods / properties declared in the class extension must be implemented
in the @implementation, just like the methods/properties found in the public
@interface.
Class extensions can also be used to redeclare a publicly readonly @property
as readwrite prior to @synthesize’ing the accessors.

Example:


Foo.h
@interface Foo:NSObject @property(readonly, copy) NSString *bar;
-(void) publicSaucing;


@end


Foo.m


@interface Foo()


@property(readwrite, copy) NSString *bar; – (void)


superSecretInternalSaucing;
@end


@implementation Foo


@synthesize bar;


.... must implement the two methods or compiler will warn .... @end
148-Copy vs mutableCopy.
copy always creates an immutable copy. mutableCopy always creates a mutable
copy.
149- Strong vs Weak

The strong and weak are new ARC types replacing retain and assign
respectively. Delegates and outlets should be weak.


A strong reference is a reference to an object that stops it from being


deallocated. In other words it creates a owner relationship.
A weak reference is a reference to an object that does not stop it from being
deallocated. In other words, it does not create an owner relationship.
150-__strong, __weak, __unsafe_unretained, __autoreleasing.
Generally speaking, these extra qualifiers don’t need to be used very often. You
might first encounter these qualifiers and others when using the migration tool.
For new projects however, you generally you won’t need them and will mostly
use strong/weak with your declared properties.
__strong – is the default so you don’t need to type it. This means any object
created using alloc/init is retained for the lifetime of its current scope. The
“current scope” usually means the braces in which the variable is declared
__weak – means the object can be destroyed at anytime. This is only useful if
the object is somehow strongly referenced somewhere else. When destroyed, a
variable with __weak is set to nil.
__unsafe_unretained – is just like __weak but the pointer is not set to nil when
the object is deallocated. Instead the pointer is left dangling.


__autoreleasing, not to be confused with calling autorelease on an object before


returning it from a method, this is used for passing objects by reference, for
example when passing NSError objects by reference such as [myObject
performOperationWithError:&tmp];
151-Types of NSTableView
Cell based and View based. In view based we can put multiple objects.
152-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
153- Difference between HTTP and HTTPS.

· HTTP stands for HyperText Transfer Protocol, whereas, HTTPS is


HyperText Transfer Protocol Secure.


· HTTP transmits everything as plan text, while HTTPS provides encrypted


communication, so that only the recipient can decrypt and read the
information. Basically, HTTPS is a combination of HTTP andSSL (Secure
Sockets Layer). This SSL is that protocol which encrypts the data.
· HTTP is fast and cheap, where HTTPS is slow and expensive.


As, HTTPS is safe it’s widely used during payment transactions or any
sensitive transactions over the internet. On the other hand, HTTP is used most
of the sites over the net, even this blogspot sites also use HTTP.


· HTTP URLs starts with “http:// “ and use port 80 by default, while
HTTPS URLs stars with “https:// “ and use port 443.


· HTTP is unsafe from attacks like man-in-the-middle and eavesdropping,


but HTTPS is secure from these sorts of attacks.
154-GCD
Grand Central Dispatch is not just a new abstraction around what we’ve
already been using, it’s an entire new underlying mechanism that makes
multithreading easier and makes it easy to be as concurrent as your code can be
without worrying about the variables like how much work your CPU cores are
doing, how many CPU cores you have and how much threads you should
spawn in response. You just use the Grand Central Dispatch API’s and it
handles the work of doing the appropriate amount of work. This is also not just
in Cocoa, anything running on Mac OS X 10.6 Snow Leopard can take
advantage of Grand Central Dispatch
( libdispatch ) because it’s included in libSystem.dylib and all you need to do
is include #import <dispatch/dispatch.h> in your app and you’ll be able to take
advantage of Grand Central Dispatch.
155-How you attain the backward compatibility?
1. Set the Base SDK to Current version of Mac (ex. 10.7)

2. Set the Deployment SDK to older version (ex.1.4)

156-Call Back.

Synchronous operations are ones that happen in step with your calling code.
Most of Cocoa works this way: you send a message to an object, say to format
a string, etc, and by the time that line of code is “done”, the operation is
complete.


But in the real world, some operations take longer than “instantaneous” (some
intensive graphics work, but mainly high or variably latency things like disk I/
O or worse, network connectivity). These operations are unpredictable, and if
the code were to block until finish, it might block indefinitely or forever, and
that’s no good.
So the way we handle this is to set up “callbacks”– you say “go off and do
this operation, and when you’re done, call this other function”. Then inside
that “callback” function, you start the second operation that depends on the
first. In this way, you’re not spinning in circles waiting, you just get called
“asynchronously” when each task is done.

157.What is the difference between setting object = nil and


[object release] ?

object = nil;
[object release]
Don't do that. You are sending a release message on a nil object that will just
do nothing. But the object that was referenced by your object is still in memory
because it has never received a release message. [object release];

object = nil;
Here you release the object, and for convenience and security, you set nil to its
reference. So you can call (by mistake of course :-) ) any method on that
object and the app won't crash.
But if you use a retained property @property(nonatomic, retain), calling :
self.object = nil;
equals to call :
[object release];
object = nil;

158.Subclass, Category and Extensions in Objective C


Today lets see what is subclassing, categories and extensions in Objective
C, and where, when and how to use these concepts.

Note: A complete working Xcode project copy is available for download,


which includes all the required examples to understand these concepts
practically at the end of this post.

1) Subclass in Objective C

Subclassing in simple words is changing the behavior of properties or


methods of an existing class or in other words subclassing is inheriting a class
and modifying the methods or properties of super class however you want.

Suppose for example consider a UITextField class, by default the


placeholder text of UITextField will be of light gray color with default
system font. If we want to change this style just subclass UITextField and
override drawPlaceholderInRect method.

Example:
Create a class of type UITextField and name it some
thing like CustomUITextFieldPlaceholderAppearance

CustomUITextFieldPlaceholderAppearance.h
#import <UIKit/UIKit.h>
@interface CustomUITextFieldPlaceholderAppearance :
UITextField @end

CustomUITextFieldPlaceholderAppearance.m
#import "CustomUITextFieldPlaceholderAppearance.h"

@implementation CustomUITextFieldPlaceholderAppearance
// override drawPlaceholderInRect method
- (void)drawPlaceholderInRect:(CGRect)rect {
// Set color and font size and style of placeholder text
[[UIColor redColor] setFill]; //set placeholder text color to
red [[self placeholder] drawInRect:rect withFont:
[UIFont fontWithName:@"verdana" size:14.0]]; //set custom font style and
size to placeholder text
}
@end

Now in your application wherever you want this custom look and feel for
placeholder text of textfield you can just import this subclass header file
(#import "CustomUITextFieldPlaceholderAppearance.h") and create an
object of this class and you are done. In addition to this look and feel the
default delegate methods and properties of UITextField will remain same.

2) Categories in Objective C

An Objective C category allows you add your own methods to an existing


class.

Categories are also called as "informal protocols".

Suppose take an example, since Foundation Framework classes such as


NSString, NSArray, NSDate etc… doesn’t have any access to modify, you
can add your own methods in to these classes by the help of a category.

Consider NSString Class and if suppose we want to add a reverse string


method to NSString class, so that in our application at any point of time any
NSString object can call this category method and get a reversed string as a
result. We can do this as below,

Note: Usually naming convention for category file is like


OriginalClassName +CategoryName

Example:
Lets create a category class with a name something like
NSString +NSString_ReverseString

NSString+NSString_ReverseString.h
#import <Foundation/Foundation.h>

@interface NSString (NSString_ReverseString)


- (NSString *)reverseString:(NSString
*)yourString; @end

NSString+NSString_ReverseString.m
#import "NSString+NSString_ReverseString.h"

@implementation NSString (NSString_ReverseString)

- (NSString *)reverseString:(NSString *)yourString


{
NSMutableString *reversedStr = [NSMutableString
stringWithCapacity: [yourString length]];

[yourString enumerateSubstringsInRange:NSMakeRange(0,
[yourString length])
options:(NSStringEnumerationReverse |
NSStringEnumerationByComposedCharacterSequences)
usingBlock:^(NSString *substring, NSRange
substringRange
, NSRange enclosingRange, BOOL *stop) {
[reversedStr appendString:substring];
}];
return reversedStr;
}
@end

Now in your application wherever you want to reverse a string then just import
this category header file (#import "NSString+NSString_ReverseString.h"
) and call our reverseString: method from any of NSString object and it
will reverse and return you the reversed string.

In the above example we have added a custom method called reverseString:


to NSString class from the help of a category.

Note that in a category you can’t add an instance variable, since methods
within a category are added to a class at runtime.

3) Extensions in Objective C

Extensions are similar to categories but the need of extension is different.


- Class extensions are often used to extend the public interface with
additional private methods or properties for use within the implementation
of the class.
- Extensions can only be added to a class for which you have the source code at
compile time (the class is compiled at the same time as the class extension).
- Extensions will be local to a class file.

The syntax to declare class extension looks like,


@interface ClassName()

@end
since no name is given in the parentheses, class extensions are often referred to
as anonymous categories.

Note Extensions can add instance variables.


Example:
@interface ABCExtension()
@property NSObject *yourProperty;
@end
the compiler will automatically synthesize the relevant accessor methods, as
well as an instance variable, inside the primary class implementation.
If you add any methods in a class extension, these must be implemented in the
primary implementation for the class.

Example:
In any of your class in implementation file(.m), say
ViewController.m @interface ViewController ()
-(void)printName:(NSString *)name;
@end

@implementation ViewController
-(void)printName:(NSString *)name
{
NSLog(@"%@",name);
}

In the above extension example printName: method is private to class


ViewController, and cannot be accessed from outside the ViewController class.
(even if you inherit since printName: is a private method their will not be any
access to this method outside the class)

You can call this extension method only inside ViewController class, as
below [self printName:@"MyName"];
Usually people will use extensions to hide private information of a
class without exposing them to access from any other class.

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

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

169.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
includeNSFileManager, 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.

171. Which is the super class of all view controller objects?


UIViewController class. The functionality for loading views, presenting them,
rotating them in response to device rotations, and several other standard system
behaviors are provided by UIViewController class.

172.What is the purpose of UIWindow object?

The presentation of one or more views on a screen is coordinated by


UIWindow object.

173.How do you change the content of your app in order to change


the views displayed in the corresponding window?

To change the content of your app, you use a view controller to change the
views displayed in the corresponding window. Remember, window
itself is never replaced.

174.Define view object.


Views along with controls are used to provide visual representation of the app
content. View is an object that draws content in a designated
rectangular area and it responds to events within that area.

182.What is data encapsulation?


Encapsulation means that your data is "self-contained" and than only your
objects can do changes to it.
Encapsulation prevents your data from being changed accidentally and
therefore avoid the introduction of nasty bugs in your programs, specially in
big projects.

Getters and setters are what make encapsulation elegant in most languages. The
point of getters and setters is to explicitly write self-documented code that
prevents accidental changes in your code. myObject.getSomeVar() and
myObject.setSomeVar("foo") explicitly tell whoever is maintaining your code
(which can and most of the time will include yourself) that your intentions are
clear.
@interface Fraction{
int _numerator;
int _denominator;
}

-(int) numerator;
-(int) denominator;

@end

@implementation Fraction

–(int) numerator
{
return _numerator;
}

–(int) denominator
{
return _denominator;
}

//setters

@end
Then we can use this class in other classes to get the numerator / denominator
of a fraction object:
//some other class
Fraction* fraction = [[Fraction
alloc]init]; //set numerator / denominator
int fractionNumerator = [fraction numerator];
What we have done above is created a Fraction object and then called it's
getNumerator method which returns an int. We capture this return value by
assigning it to fractionNumerator.

183.What is Polymorphism?

The word polymorphism means having many forms. Typically, polymorphism


occurs when there is a hierarchy of classes and they are related by inheritance.
Objective-C polymorphism means that a call to a member function will cause a
different function to be executed depending on the type of object that invokes
the function.
Consider the example, we have a class Shape that provides the basic interface
for all the shapes. Square and Rectangle are derived from the base class Shape.
We have the method printArea that is going to show about the OOP feature
polymorphism.
#import <Foundation/Foundation.h>

@interface Shape : NSObject

{
CGFloat area;
}

- (void)printArea;
- (void)calculateArea;
@end

@implementation Shape

- (void)printArea{
NSLog(@"The area is %f", area);
}

- (void)calculateArea{

@end

@interface Square : Shape


{
CGFloat length;
}
- (id)initWithSide:(CGFloat)side;

- (void)calculateArea;

@end

@implementation Square

- (id)initWithSide:
(CGFloat)side{ length = side;
return self;
}

- (void)calculateArea{ area
= length * length;
}

- (void)printArea{
NSLog(@"The area of square is %f", area);
}

@end

@interface Rectangle : Shape


{
CGFloat length;
CGFloat breadth;
}
- (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth;

@end

@implementation Rectangle

- (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth{
length = rLength;
breadth = rBreadth;
return self;
}

- (void)calculateArea{ area
= length * breadth;
}
@end

int main(int argc, const char * argv[])


{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Shape *square = [[Square alloc]initWithSide:10.0]; [square
calculateArea];
[square printArea];
Shape *rect = [[Rectangle alloc]
initWithLength:10.0 andBreadth:5.0];
[rect calculateArea];
[rect printArea];
[pool drain];
return 0;
}
When the above code is compiled and executed, it produces the following
result:
2013-09-22 21:21:50.785 Polymorphism[358:303] The area of square is
100.000000
2013-09-22 21:21:50.786 Polymorphism[358:303] The area is 50.000000
In the above example based on the availability of the method calculateArea and
printArea, either the method in the base class or the derived class executed.
Polymorphism handles the switching of methods between the base class
and derived class based on the method implementation of the two classes.

184.Abstract class for Objective-C?

There are no abstract classes but you can produce something similar using a
combination of a class and a protocol (which is similar to Java's interface). First
divide up your abstract class into those methods you wish to provide default
implementations for and those you require sub-classes to implement. Now
declare the default methods in an @interface and implement them in an
@implementation, and declare the required methods in an @protocol. Finally
derive your sub-classes from class<protocol> - a class which implements the
protocol. For example:
@interface MyAbstract

- (void)

methodWithDefaultImplementation; @end

@protocol MyAbstract
- (void)

methodSubclassMustImplement; @end

@implementation MyAbstract

- (void) methodWithDefaultImplementation { ... }

@end

@interface MyConcreteClass: MyAbstract<MyAbstract>


...
@end

@implementation MyConcreteClass

// must implement abstract methods in protocol -


(void) methodSubclassMustImplement { ... }

@end
If you are concerned over using the same name for a class and a protocol look
at Cocoa where NSObject follows this pattern…

188.What is responder chain?

Suppose you have a hierarchy of views such like there is superview A which
have subview B and B has a subview C. Now you touch on inner most
view C. The system will send touch event to subview C for handling this
event. If C View does not want to handle this event, this event will be
passed to its superview B (next responder). If B also does not want to
handle this touch event it will pass on to superview A. All the view which
can respond to touch events are called responder chain. A view can also
pass its events to uiviewcontroller. If view controller also does not want
to respond to touch event, it is passed to application object which
discards this event.

189.the advantages and disadvantages about synchronous


versus asynchronous connections.

That’s it, pretty fast and easy, but there are a lot of caveats :

• The most important problem is that the thread which called this method will
be blocked until the connection finish or timeout, so we surely don’t
want to start the connection on the main thread to avoid freezing the UI.
That means we need to create a new thread to handle the connection, and
all programmers know that threading is hard.

• Cancellation, it’s not possible to cancel a synchronous connection, which


is bad because users like to have the choice to cancel an operation if
they think it takes too much time to execute.
• Authentication, there is no way to deal with authentication challenges.

• It’s impossible to parse data on the fly.

So let’s put it up straight, avoid using synchronousNSURLConnection, there is


absolutely no benefit of using it.

It’s clear that asynchronous connections give us more control :

• You don’t have to create a new thread for the connection because your main
thread will not be blocked.

• You can easily cancel the connection just by calling the cancelmethod.

• If you need authentication just implement the required delegate methods.

• Parsing data on the fly is easy.

So clearly we have a lot of more control with this, and the code is really not
difficult.

Even better, we don’t have to handle the creation of a new thread, which is a
good thing, because you know, threading is hard.

Well, if you read me until here, you should be convinced to use asynchronous
connections, and forget about synchronous ones. They clearly give us
more control and possibilities and, in some case can spare us to create
new thread.

So I encourage you to move away from synchronous connections, just think of


them as evil.

197.Selectors

In Objective-C, selector has two meanings. It can be used to refer simply to the
name of a method when it’s used in a source-code message to an object.
It also, though, refers to the unique identifier that replaces the name when
the source code is compiled. Compiled selectors are of type SEL. All
methods with the same name have the same selector. You can use a
selector to invoke a method on an object—this provides the basis for the
implementation of the target-action design pattern in Cocoa.

[friend performSelector:@selector(gossipAbout:) withObject:aNeighbor];

is equivalent to:

[friend gossipAbout:aNeighbor];

198.Class Introspection

· Determine whether an objective-C object is an instance of a

class [obj isMemberOfClass:someClass];

· Determine whether an objective-C object is an instance of a class or


its descendants

[obj isKindOfClass:someClass];
· The version of a class

[MyString version]

· Find the class of an Objective-C object

Class c = [obj1 class]; Class c = [NSString class];

· Verify 2 Objective-C objects are of the same class

[obj1 class] == [obj2 class]

217.Strong vs Weak
The strong and weak are new ARC types replacing retain and
assign respectively.

Delegates and outlets should be weak.

A strong reference is a reference to an object that stops it from being


deallocated. In other words it creates a owner relationship.
A weak reference is a reference to an object that does not stop it from being
deallocated. In other words, it does not create an owner relationship.

218.difference between udid and device token?

The device ID and UDID are different names for the same thing. The device
token is used for a server to send notifications to that device using Apple's
Push Notification service - it lets the APN server know which device you're
talking about, but doesn't have any meaning outside that context.

219.how to check crash reports client in ios app?

Using Testflight

220.How to sort an array of strings alphabetically in objective c.

localizedCaseInsensitiveCompare

221.What is the difference between NSString and NSMutableString?

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

s = [s stringByAppendingString:@"World"];
and other code like this
NSMutableString *ms = [[NSMutableString alloc] initWithString:@"Hello"];

[ms appendString:@"World"];
Both of these, functionally, do the same thing except for one difference - the
top code block leaks. -[NSString stringByAppendingString:] generates a new
immutable NSString object which you then tell the pointer s to point to. In the
process, however, you orphan the NSString object that s originally pointed to.
Replacing the line as follows would get rid of the leak:
s = [[s autorelease] stringByAppendingString:@“World"];
222.How to check whether a substring exists in a string?

NSString *originalString;
NSString *compareString;
Let your string in stored in originalString and the substring that you want
to compare is strored in compareString.
if ([originalString rangeOfString:compareString].location==NSNotFound)
{
NSLog(@"Substring Not Found");

}
else
{
NSLog(@"Substring Found Successfully");
}

223.Apple Push Notification Services?

1 An app enables push notifications. The user has to confirm that he wishes
to receive these notifications.
2. The app receives a “device token”. You can think of the device token
as the address that push notifications will be sent to.
3. The app sends the device token to your server.
4. When something of interest to your app happens, the server sends a push
notification to the Apple Push Notification Service, or APNS for short.
5. APNS sends the push notification to the user’s device.
When the user’s device receives the push notification, it shows an alert, plays a
sound and/or updates the app’s icon. The user can launch the app from the alert.
The app is given the contents of the push notification and can handle it as it
sees fit.
224.What is Concurrency?
• Doing multiple things at the same time.
• Taking advantage of number of cores available in multicore CPUs.
• Running multiple programs in parallel.

225.Objectives of Concurrency
• Running program in background without hogging CPU.
• Define Tasks, Define Rules and let the system take the responsibility of
performing them.
• Improve responsiveness by ensuring that the main thread is free to respond
to user events.
• Leverage more cores to do more work in the same amount of time.

226.Problems with the Threaded Approach


• Threads are low level tool that needs to be managed manually.
• Creating a correct threading solution is difficult.
• Thread synchronization adds complexity to the project
• Incorrectly implemented threading solution might make the system even
worse
• Scalability is an issue when it comes to utilizing multiple available cores.

227.When to Use Threads?


• Threads are still a good way to implement code that must run in real time
• Dispatch Queues make every attempt to run their tasks as fast as possible
but they do not address the real time constraints

228.Operations and Operation Queue


• Object oriented way to encapsulate work that needs to be performed
asynchronously
• An Operation object is an instance of NSOperation(abstract) class.
• NSOperation class has two concrete subclasses that can be used as is
• NSInvocationOperation (used to execute a method)
• NSBlockOperation (used for executing one or more blocks
concurrently)
• An operation can be executed individually/manually by calling its start
method or it can be added to an OperationQueue.

229.NSInvocationOperation
• A class we can use as-is to create an operation object based on an object and
selector from your application.
• We can use this class in cases where we have an existing method that
already performs the needed task. Because it does not require subclassing,
we can also use this class to create operation objects in a more dynamic
fashion.

230.NSBlockOperation
• A class we use as-is to execute one or more block objects concurrently.
• Because it can execute more than one block, a block operation object
operates using a group semantic; only when all of the associated blocks have
finished executing is the operation itself considered finished.
Grand Central Dispatch
Grand Central Dispatch provides queues to which the application can submit tasks
in the form of block objects. The block of code submitted to dispatch queues are
executed on a pool of threads managed by the system. Each task can either be
executed synchronously or asynchronously. In case of synchronous execution the
program waits for the execution to be finished before the call returns. In case of
asynchronous call the method call returns immediately.
Dispatch Queues can be serial or concurrent. In case of serial dispatch queues the
work items are executed one at a time and in case of concurrent although the tasks
are dequeued in order but they run in parallel and can finish in any order.
Main Queue – When the app is launched the system automatically creates a special
queue called as main queue. Work items on the main queue is executed serially on
the applications main thread.
down vote

231.When to Use NSOperation


The NSOperation API is great for encapsulating well-defined blocks of
functionality. You could, for example, use an NSOperation subclass to encapsulate
the login sequence of an application.
Dependency management is the icing on the cake. An operation can have
dependencies to other operations and that is a powerful feature Grand Central
Dispatch lacks. If you need to perform several tasks in a specific order, then
operations are a good solution.
You can go overboard with operations if you are creating dozens of operations in a
short timeframe. This can lead to performance problems due to the overhead
inherent to the NSOperation API.

232.When to Use Grand Central Dispatch


Grand Central Dispatch is ideal if you just need to dispatch a block of code to a
serial or concurrent queue.
If you don’t want to go through the hassle of creating an NSOperation subclass for
a trivial task, then Grand Central Dispatch is a great alternative. Another benefit of
Grand Central Dispatch is that you can keep related code together. Take a look at
the following example.
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data,
response, error) -> Void in
// Process Response
...

dispatch_async(dispatch_get_main_queue(), { () -> Void in


// Update User Interface
...
})
})
In the completion handler of the data task, we process the response and update the
user interface by dispatching a closure (or block) to the main queue. This is
necessary because we don’t know which thread the completion handler is executed
on and it most likely is a background thread.
Concurrency is dividing up the execution paths of your program so that they are
possibly running at the same time. The common terminology: process, thread,
multithreading, and others. Terminology;
Process, An instance of an executing app
Thread, Path of execution for code
Multithreading, Multiple threads or multiple paths of execution running at
the same time.
Concurrency, Execute multiple tasks at the same time in a scalable manner.
Queues, Queues are lightweight data structures that manage objects in the
order of First-in, First-out (FIFO).
Synchronous vs Asynchronous tasks
GCD is a library that provides a low-level API to run tasks concurrently while
managing threads behind the scenes. Terminology;
Dispatch Queues, A dispatch queue is responsible for executing a task in the
first-in, first-out order.
Serial Dispatch Queue A serial dispatch queue runs tasks one at a time.
Concurrent Dispatch Queue A concurrent dispatch queue runs as many tasks
as it can without waiting for the started tasks to finish.
Main Dispatch Queue A globally available serial queue that executes tasks
on the application’s main thread.

234. Explain what is Swift Programming Language?


Swift is a programming language and system for creating applications for iOS and
OS X. It is an innovative programming language for Cocoa and Cocoa Touch.

235. Explain how you define variables in Swift language?


Variables and constants must be declared before they are used. You announce
constants with the let keyword and variables with the var keyword. Both variables
and dictionaries are described using brackets. For example,
Var Guru99 = “This is Guru99”
Let ksomeconstant = 30

236. Explain how Swift program is deployed?


Swift program deploys the application in a Tomcat installation by default. The
deploy script bundles the client code into JavaScript, gathers all the server side
classes required and packages them into file Hello.war. This file together with a
GWT jar and a Swift runtime jar is copied into the Tomcat installation. If
CATALINA_HOME is not set, these files require to be copied manually.

237. Mention what are the features of Swift Programming?


• It eliminates entire classes of unsafe code
• Variables are always initialized before use
• Arrays and integers are checked for overflow
• Memory is managed automatically
• Instead of using “if” statement in conditional programming, swift has
“switch” function

238. Mention what is the difference between Swift and ‘Objective-C’


language?
Difference between ‘C’ and ‘Swift’ language is that
Swift
• In a swift, the variable and constants are declared before their use
• You have to use “let” keyword for constant and “var” keyword for variable
• There is no need to end code with semi-colon
• Concatenating strings is easy in swift and allows to make a new string from
a mix of constants, literals, variables, as well as expressions
• Swift does not require to create a separate interface like Objective C. You
can define classes in a single file (.swift)
• Swift enables you to define methods in class, structure or enumeration
• In Swift, you use “ +=” Operator to add an item

Objective-C
• In objective C, you have to declare variable as NSString and constant as int
• In objective C, variable is declared as “ and constant as “
• The code ends with semi-colon
• In objective C, you have to choose between NSMutableString and NSString
for string to be modified.
• For classes, you create separate interface (.h) and implementation (.m) files
for classes
• Objective does not allow this
• In C, you use “addObject”: method of NSMutable array to append a new
item to an array

239. Mention what are the type of integers does Swift have?
Swift provides unsigned and signed integers in 8, 16, 32 and 64 bit forms. Similar
to C these integers follow a naming convention. For instance, unsigned integer is
denoted by type UInt8 while 32 bit signed integer will be denoted by type Int32.

240. Mention what is the Floating point numbers and what are the types of
floating number in Swift?
Floating numbers are numbers with a fractional component, like 3.25169 and
-238.21. Floating point types can represent a wider range of values than integer
types. There are two signed floating point number
• Double: It represents a 64 bit floating point number, it is used when floating
point values must be very large
• Float: It represents a 32 bit floating point number, it is used when floating
point values does not need 64 bit precision

241. Explain how multiple line comment can be written in swift?


Multiple line comment can be written as forward-slash followed by an asterisk (/
*) and end with an asterisk followed by a forward slash (*/).

242. What is de-initializer and how it is written in Swift?


A de-initializer is declared immediately before a class instance is de-allocated.
You write de-initializer with the deinit keyword. De-initializer is written without
any parenthesis, and it does not take any parameters. It is written as
deinit {
// perform the deinitialization
}

243.Mention what are the collection types available in Swift?


In Swift, collection types come in two varieties Array and Dictionary
• Array: You can create an Array of a single type or an array with multiple
types. Swift usually prefers the former one
Example for single type array is,
Var cardName : [String] = [ “Robert” , “Lisa” , “Kevin”]
// Swift can infer [String] so we can also write it as:
Var cardNames = [ “Robert”, “Lisa”, “Kevin”] // inferred as [String]
To add an array you need to use the subscript println(CardNames[0])
• Dictionary: It is similar to a Hash table as in other programming language. A
dictionary enables you to store key-value pairs and access the value by
providing the key
var cards = [ “Robert”: 22, “Lisa” : 24, and “Kevin”: 26]

244.List out what are the control transfer statements used in Swift?
Control transfer statements used in Swift includes
• Continue
• Break
• Fallthrough
• Return

245. Explain what is optional chaining?


Optional chaining is a process of querying and calling properties. Multiple queries
can be chained together, and if any link in the chain is nil then, the entire chain
fails.

246. How base-class is defined in Swift?


In Swift the classes are not inherited from the base class and the classes that you
define without specifying its superclass, automatically becomes the base-class.

247. Explain what Lazy stored properties is and when it is useful?


Lazy stored properties are used for a property whose initial values is not calculated
until the first time it is used. You can declare a lazy stored property by writing the
lazy modifier before its declaration. Lazy properties are useful when the initial
value for a property is reliant on outside factors whose values are unknown.

248. Mention what is the characteristics of Switch in Swift?


• It supports any kind of data, and not only synchronize but also checks for
equality
• When a case is matched in switch, the program exists from the switch case
and does not continue checking next cases. So you don’t need to explicitly
break out the switch at the end of case
• Switch statement must be exhaustive, which means that you have to cover
all possible values for your variable
• There is no fallthrough in switch statements and therefore break is not
required

249. What is the question mark ? in Swift?


The question mark ? is used during the declaration of a property, as it tells the
compiler that this property is optional. The property may hold a value or not, in the
latter case it's possible to avoid runtime errors when accessing that property by
using ?. This is useful in optional chaining (see below) and a variant of this
example is in conditional clauses.
var optionalName : String? = “John"
if optionalName != nil {
print(“Your name is \(optionalName!)”)
}

250.What is the use of double question marks ???


To provide a default value for a variable.
let missingName : String? = nil
let realName : String? = “John Doe"
let existentName : String = missingName ?? realName

251.What is the use of exclamation mark !?


Highly related to the previous keywords, the ! is used to tell the compiler that I
know definitely, this variable/constant contains a value and please use it (i.e.
please unwrap the optional). From question 1, the block that executes the if
condition is true and calls a forced unwrapping of the optional's value. There is a
method for avoiding forced unwrapping which we will cover below.

252. What is type aliasing in Swift?


This borrows very much from C/C++. It allows you to alias a type, which can be
useful in many particular contexts.
typealias AudioSample = UInt16

253. What is the difference between functions and methods in Swift?


Both are functions in the same terms any programmer usually knows of it. That is,
self-contained blocks of code ideally set to perform a specific task. Functions are
globally scoped while methods belong to a certain type.

254.What are optional binding and optional chaining in Swift?


Optional bindings or chaining come in handy with properties that have been
declared as optional. Consider this example:
class Student {
var courses : [Course]?
}
let student = Student()
Optional chaining
If you were to access the courses property through an exclamation mark (!) , you
would end up with a runtime error because it has not been initialized yet. Optional
chaining lets you safely unwrap this value by placing a question mark (?), instead,
after the property, and is a way of querying properties and methods on an optional
that might contain nil. This can be regarded as an alternative to forced unwrapping.
Optional binding
Optional binding is a term used when you assign temporary variables from
optionals in the first clause of an if or while block. Consider the code block below
when the property courses have yet not been initialized. Instead of returning a
runtime error, the block will gracefully continue execution.
if let courses = student.courses {
print("Yep, courses we have")
}
The code above will continue since we have not initialized the courses array yet.
Simply adding:
init() { courses = [Course]() }
Will then print out "Yep, courses we have.”

255. What's the syntax for external parameters?


The external parameter precedes the local parameter name.
func yourFunction(externalParameterName localParameterName :Type, ....) { .... }
A concrete example of this would be:
func sendMessage(from name1 :String, to name2 :String) { print("Sending
message from \(name1) to \(name2)") }

256. How should one handle errors in Swift?


The method for handling errors in Swift differ a bit from Objective-C. In Swift, it's
possible to declare that a function throws an error. It is, therefore, the caller's
responsibility to handle the error or propagate it. This is similar to how Java
handles the situation.
You simply declare that a function can throw an error by appending the throws
keyword to the function name. Any function that calls such a method must call it
from a try block.
func canThrowErrors() throws -> String

//How to call a method that throws an error


try canThrowErrors()

//Or specify it as an optional


let maybe = try? canThrowErrors()</pre>
Bonus question: What is a guard statement in Swift?
Guard statements are a nice little control flow statement that can be seen as a great
addition if you're into a defensive programming style (which you should!). It
basically evaluates a boolean condition and proceeds with program execution if
the evaluation is true. A guard statement always has an else clause, and it must exit
the code block if it reaches there.
guard let courses = student.courses! else {
return
}

257.On a UITableViewCell constructor:


- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString
*)reuseIdentifier
What is the reuseIdentifier used for?
The reuseIdentifier is used to indicate that a cell can be re-used in a UITableView.
For example when the cell looks the same, but has different content. The
UITableView will maintain an internal cache of UITableViewCell’s with the
reuseIdentifier and allow them to be re-used when
dequeueReusableCellWithIdentifier: is called. By re-using table cell’s the scroll
performance of the tableview is better because new views do not need to be
created.

258.Explain the difference between atomic and nonatomic synthesized


properties?
Atomic and non-atomic refers to whether the setters/getters for a property will
atomically read and write values to the property. When the atomic keyword is used
on a property, any access to it will be “synchronized”. Therefore a call to the getter
will be guaranteed to return a valid value, however this does come with a small
performance penalty. Hence in some situations nonatomic is used to provide faster
access to a property, but there is a chance of a race condition causing the property
to be nil under rare circumstances (when a value is being set from another thread
and the old value was released from memory but the new value hasn’t yet been
fully assigned to the location in memory for the property).
259.Explain the difference between copy and retain?
Retaining an object means the retain count increases by one. This means the
instance of the object will be kept in memory until it’s retain count drops to zero.
The property will store a reference to this instance and will share the same instance
with anyone else who retained it too. Copy means the object will be cloned with
duplicate values. It is not shared with any one else.

260.What is method swizzling in Objective C and why would you use it?
Method swizzling allows the implementation of an existing selector to be switched
at runtime for a different implementation in a classes dispatch table. Swizzling
allows you to write code that can be executed before and/or after the original
method. For example perhaps to track the time method execution took, or to insert
log statements
#import "UIViewController+Log.h"
@implementation UIViewController (Log)
+ (void)load {
static dispatch_once_t once_token;
dispatch_once(&once_token, ^{
SEL viewWillAppearSelector = @selector(viewDidAppear:);
SEL viewWillAppearLoggerSelector = @selector(log_viewDidAppear:);
Method originalMethod = class_getInstanceMethod(self,
viewWillAppearSelector);
Method extendedMethod = class_getInstanceMethod(self,
viewWillAppearLoggerSelector);
method_exchangeImplementations(originalMethod, extendedMethod);
});
}
- (void) log_viewDidAppear:(BOOL)animated {
[self log_viewDidAppear:animated];
NSLog(@"viewDidAppear executed for %@", [self class]);
}
@end

261.What’s the difference between not-running, inactive, active, background


and suspended execution states?
• Not running: The app has not been launched or was running but was
terminated by the system.
• Inactive: The app is running in the foreground but is currently not receiving
events. (It may be executing other code though.) An app usually stays in this
state only briefly as it transitions to a different state.
• Active: The app is running in the foreground and is receiving events. This is
the normal mode for foreground apps.
• Background: The app is in the background and executing code. Most apps
enter this state briefly on their way to being suspended. However, an app
that requests extra execution time may remain in this state for a period of
time. In addition, an app being launched directly into the background enters
this state instead of the inactive state.
• Suspended: The app is in the background but is not executing code. The
system moves apps to this state automatically and does not notify them
before doing so. While suspended, an app remains in memory but does not
execute any code. When a low-memory condition occurs, the system may
purge suspended apps without notice to make more space for the foreground
app.

262.Can you spot the bug in the following code and suggest how to fix it:
@interface MyCustomController : UIViewController

@property (strong, nonatomic) UILabel *alert;

@end

@implementation MyCustomController

- (void)viewDidLoad {
CGRect frame = CGRectMake(100, 100, 100, 50);
self.alert = [[UILabel alloc] initWithFrame:frame];
self.alert.text = @"Please wait...";
[self.view addSubview:self.alert];
dispatch_async(
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
0),
^{
sleep(10);
self.alert.text = @"Waiting over";
}
);
}

@end
All UI updates must be done on the main thread. In the code above the update to
the alert text may or may not happen on the main thread, since the global dispatch
queue makes no guarantees . Therefore the code should be modified to always run
the UI update on the main thread
dispatch_async(
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
^{
sleep(10);
dispatch_async(dispatch_get_main_queue(), ^{
self.alert.text = @"Waiting over";
});
});

263.What considerations do you need when writing a UITableViewController


which shows images downloaded from a remote server?
This is a very common task in iOS and a good answer here can cover a whole host
of knowledge. The important piece of information in the question is that the
images are hosted remotely and they may take time to download, therefore when it
asks for “considerations”, you should be talking about:
• Only download the image when the cell is scrolled into view, i.e. when
cellForRowAtIndexPath is called.
• Downloading the image asynchronously on a background thread so as not to
block the UI so the user can keep scrolling.
• When the image has downloaded for a cell we need to check if that cell is
still in the view or whether it has been re-used by another piece of data. If
it’s been re-used then we should discard the image, otherwise we need to
switch back to the main thread to change the image on the cell.
Other good answers will go on to talk about offline caching of the images, using
placeholder images while the images are being downloaded.

264.What is KVC and KVO? Give an example of using KVC to set a value.
KVC stands for Key-Value Coding. It's a mechanism by which an object's
properties can be accessed using string's at runtime rather than having to statically
know the property names at development time. KVO stands for Key-Value
Observing and allows a controller or class to observe changes to a property value.
Let's say there is a property name on a class:
@property (nonatomic, copy) NSString *name;
We can access it using KVC:
NSString *n = [object valueForKey:@"name"]
And we can modify it's value by sending it the message:
[object setValue:@"Mary" forKey:@"name"]
265.What are blocks and how are they used?
Blocks are a way of defining a single task or unit of behavior without having to
write an entire Objective-C class. Under the covers Blocks are still Objective C
objects. They are a language level feature that allow programming techniques like
lambdas and closures to be supported in Objective-C. Creating a block is done
using the ^ { } syntax:
myBlock = ^{
NSLog(@"This is a block");
}
It can be invoked like so:
myBlock();
It is essentially a function pointer which also has a signature that can be used to
enforce type safety at compile and runtime. For example you can pass a block with
a specific signature to a method like so:
- (void)callMyBlock:(void (^)(void))callbackBlock;
If you wanted the block to be given some data you can change the signature to
include them:
- (void)callMyBlock:(void (^)(double, double))block {
...
block(3.0, 2.0);
}

266.What mechanisms does iOS provide to support multi-threading?


• NSThread creates a new low-level thread which can be started by calling the
start method.
NSThread* myThread = [[NSThread alloc] initWithTarget:self
selector:@selector(myThreadMainMethod:)
object:nil];
[myThread start];
• NSOperationQueue allows a pool of threads to be created and used to
execute NSOperations in parallel. NSOperations can also be run on the main
thread by asking NSOperationQueue for the mainQueue.
NSOperationQueue* myQueue = [[NSOperationQueue alloc] init];
[myQueue addOperation:anOperation];
[myQueue addOperationWithBlock:^{
/* Do something. */
}];
• GCD or Grand Central Dispatch is a modern feature of Objective-C that
provides a rich set of methods and API's to use in order to support common
multi-threading tasks. GCD provides a way to queue tasks for dispatch on
either the main thread, a concurrent queue (tasks are run in parallel) or a
serial queue (tasks are run in FIFO order).
dispatch_queue_t myQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(myQueue, ^{
printf("Do some work here.\n");
});

267.What is the Responder Chain?


When an event happens in a view, for example a touch event, the view will fire the
event to a chain of UIResponder objects associated with the UIView. The first
UIResponder is the UIView itself, if it does not handle the event then it continues
up the chain to until UIResponder handles the event. The chain will include
UIViewControllers, parent UIViews and their associated UIViewControllers, if
none of those handle the event then the UIWindow is asked if it can handle it and
finally if that doesn't handle the event then the UIApplicationDelegate is asked.

268.What’s your preference when writing UI's? Xib files, Storyboards or


programmatic UIView?
There's no right or wrong answer to this, but it's great way of seeing if you
understand the benefits and challenges with each approach. Here's the common
answers I hear:
• Storyboard's and Xib's are great for quickly producing UI's that match a
design spec. They are also really easy for product managers to visually see
how far along a screen is.
• Storyboard's are also great at representing a flow through an application and
allowing a high-level visualization of an entire application.
• Storyboard's drawbacks are that in a team environment they are difficult to
work on collaboratively because they're a single file and merge's become
difficult to manage.
• Storyboards and Xib files can also suffer from duplication and become
difficult to update. For example if all button's need to look identical and
suddenly need a color change, then it can be a long/difficult process to do
this across storyboards and xibs.
• Programmatically constructing UIView's can be verbose and tedious, but it
can allow for greater control and also easier separation and sharing of code.
They can also be more easily unit tested.
Most developers will propose a combination of all 3 where it makes sense to share
code, then re-usable UIViews or Xib files.

269.How would you securely store private user data offline on a device? What
other security best practices should be taken?
Again there is no right answer to this, but it's a great way to see how much a
person has dug into iOS security. If you're interviewing with a bank I'd almost
definitely expect someone to know something about it, but all companies need to
take security seriously, so here's the ideal list of topics I'd expect to hear in an
answer:
• If the data is extremely sensitive then it should never be stored offline on the
device because all devices are crackable.
• The keychain is one option for storing data securely. However it's
encryption is based on the pin code of the device. User's are not forced to set
a pin, so in some situations the data may not even be encrypted. In addition
the users pin code may be easily hacked.
• A better solution is to use something like SQLCipher which is a fully
encrypted SQLite database. The encryption key can be enforced by the
application and separate from the user's pin code.
Other security best practices are:
• Only communicate with remote servers over SSL/HTTPS.
• If possible implement certificate pinning in the application to prevent man-
in-the-middle attacks on public WiFi.
• Clear sensitive data out of memory by overwriting it.
• Ensure all validation of data being submitted is also run on the server side.

270A product manager in your company reports that the application is


crashing. What do you do?
This is a great question in any programming language and is really designed to see
how you problem solve. You're not given much information, but some interviews
will slip you more details of the issue as you go along. Start simple:
• get the exact steps to reproduce it.
• find out the device, iOS version.
• do they have the latest version?
• get device logs if possible.
Once you can reproduce it or have more information then start using tooling. Let's
say it crashes because of a memory leak, I'd expect to see someone suggest using
Instruments leak tool. A really impressive candidate would start talking about
writing a unit test that reproduces the issue and debugging through it.
Other variations of this question include slow UI or the application freezing. Again
the idea is to see how you problem solve, what tools do you know about that
would help and do you know how to use them correctly.
271.What is AutoLayout? What does it mean when a constraint is "broken"
by iOS?
AutoLayout is way of laying out UIViews using a set of constraints that specify
the location and size based relative to other views or based on explicit values.
AutoLayout makes it easier to design screens that resize and layout out their
components better based on the size and orientation of a screen. _Constraint_s
include:
• setting the horizontal/vertical distance between 2 views
• setting the height/width to be a ratio relative to a different view
• a width/height/spacing can be an explicit static value
Sometimes constraints conflict with each other. For example imagine a UIView
which has 2 height constraints: one says make the UIView 200px high, and the
second says make the height twice the height of a button. If the iOS runtime can
not satisfy both of these constraints then it has to pick only one. The other is then
reported as being "broken" by iOS.

272.Readers-Writers

Multiple threads reading at the same time while there should be only one thread
writing. The solution to the problem is a readers-writers lock which allows
concurrent read-only access and an exclusive write access. Terminology;
Race Condition A race condition occurs when two or more threads can
access shared data and they try to change it at the same time.
Deadlock A deadlock occurs when two or sometimes more tasks wait for
the other to finish, and neither ever does.
Readers-Writers problem Multiple threads reading at the same time while
there should be only one thread writing.
Readers-writer lock Such a lock allows concurrent read-only access to the
shared resource while write operations require exclusive access.
Dispatch Barrier Block Dispatch barrier blocks create a serial-style
bottleneck when working with concurrent queues.

273.What is the difference Non-Escaping and Escaping Closures ?


The lifecycle of a non-escaping closure is simple:
Pass a closure into a function
The function runs the closure (or not)
The function returns
Escaping closure means, inside the function, you can still run the closure (or not);
the extra bit of the closure is stored some place that will outlive the function. There
are several ways to have a closure escape its containing function:
Asynchronous execution: If you execute the closure asynchronously on a
dispatch queue, the queue will hold onto the closure for you. You have no
idea when the closure will be executed and there’s no guarantee it will
complete before the function returns.
Storage: Storing the closure to a global variable, property, or any other bit of
storage that lives on past the function call means the closure has also
escaped.
274. Explain [weak self] and [unowned self] ?
unowned does the same as weak with one exception: The variable will not become
nil and therefore the variable must not be an optional.
But when you try to access the variable after its instance has been deallocated.
That means, you should only use unowned when you are sure, that this variable
will never be accessed after the corresponding instance has been deallocated.
However, if you don’t want the variable to be weak AND you are sure that it can’t
be accessed after the corresponding instance has been deallocated, you can use
unowned.
By declaring it [weak self] you get to handle the case that it might be nil inside the
closure at some point and therefore the variable must be an optional. A case for
using [weak self] in an asynchronous network request, is in a view controller
where that request is used to populate the view.

275.What makes React Native special for iOS?


(Unlike PhoneGap) with React Native your application logic is written and
runs in JavaScript, whereas your application UI is fully native; therefore you
have none of the compromises typically associated with HTML5 UI.
Additionally (unlike Titanium), React introduces a novel, radical and highly
functional approach to constructing user interfaces. In brief, the application
UI is simply expressed as a function of the current application state.

276.Please explain final keyword into the class ?


By adding the keyword final in front of the method name, we prevent the method
from being overridden. If we can replace the final class keyword with a single
word static and get the same behavior.

277.What is the difference open & public access level ?


open allows other modules to use the class and inherit the class; for members, it
allows others modules to use the member and override it.
public only allows other modules to use the public classes and the public members.
Public classes can no longer be subclassed, nor public members can be overridden.

278.What is the difference fileprivate &private access level ?


fileprivate is accessible within the current file, private is accessible within the
current declaration.

279.What is Internal access ?


Internal access enables entities to be used within any source file from their
defining module, but not in any source file outside of the module.
Internal access is the default level of access. So even though we haven’t been
writing any access control specifiers in our code, our code has been at an internal
level by default.

The Five Access Levels of Swift 4


To recap Swift 4 has the same five access levels as Swift 3. In order from most
open to most restricted:
• open you can access open classes and class members from any source file in
the defining module or any module that imports that module. You can
subclass an open class or override an open class member both within their
defining module and any module that imports that module.
• public allows the same access as open - any source file in any module - but
has more restrictive subclassing and overriding. You can only subclass a
public class within the same module. A public class member can only be
overriden by subclasses in the same module. This is important if you are
writing a framework. If you want a user of that framework to be able to
subclass a class or override a method you must make it open.
• internal allows use from any source file in the defining module but not from
outside that module. This is the default access level.
• fileprivate allows use only within the defining source file.
• private allows use only from the enclosing declaration and new in Swift 4,
to any extensions of that declaration in the same source file.
. final Use final when you know that a declaration does not need to be
overridden. The final keyword is a restriction on a class, method, or
property that indicates that the declaration cannot be overridden. This allows
the compiler to safely elide dynamic dispatch indirection.
Notes:
• Remember that your application target is its own module and that internal
access is the default. Your classes, structs, enums, properties and methods
are all accessibile within the application module by default unless you
choose to restrict access.
• As with Swift 3 you can add final to any access level, except open, to
prevent subclassing or overriding of a class method or property.

280.What is the benefit writing tests in iOS apps ?


Writing tests first gives us a clear perspective on the API design, by getting
into the mindset of being a client of the API before it exists.
Good tests serve as great documentation of expected behavior.
It gives us confidence to constantly refactor our code because we know that
if we break anything our tests fail.
If tests are hard to write its usually a sign architecture could be improved.
Following RGR ( Red — Green — Refactor ) helps you make improvements
early on.

281.Explain If let structure


If let is a special structure in Swift that allows you to check if an Optional rhs
holds a value, and in case it does — unwraps and assigns it to the lhs.

282.What is bitcode ?
It’s a very general encoding format that we can use for XML-type purposes. It’s a
self-describing file format and multiple different things can be encoded in Bitcode.
Apple Watch apps have to be in Bitcode and Apple TV is required. iOS is still
optional. The advantage is compiler keeps getting better.
283. Explain Swift Standart Library Protocol ?
There are a few different protocol. Equatable protocol, that governs how we can
distinguish between two instances of the same type. That means we can analyze. If
we have a specific value is in our array. The comparable protocol, to compare two
instances of the same type and sequence protocol: prefix(while:) and drop(while:)
[SE-0045].
Swift 4 introduces a new Codable protocol that lets us serialize and deserialize
custom data types without writing any special code.

284.What is the difference SVN and Git ?


SVN relies on a centralised system for version management. It’s a central
repository where working copies are generated and a network connection is
required for access.
Git relies on a distributed system for version management. You will have a local
repository on which you can work, with a network connection only required to
synchronise.

285.What is Alamofire doing ?


Alamofire provides chainable request/response methods, JSON parameter and
response serialization, authentication, and many other features.

286. REST, HTTP, JSON — What’s that?


HTTP is the application protocol, or set of rules, web sites use to transfer data
from the web server to client. The client (your web browser or app) use to indicate
the desired action:
GET: Used to retrieve data, such as a web page, but doesn’t alter any data
on the server.
HEAD: Identical to GET but only sends back the headers and none of the
actual data.
POST: Used to send data to the server, commonly used when filling a form
and clicking submit.
PUT: Used to send data to the specific location provided.
DELETE: Deletes data from the specific location provided.
REST, or REpresentational State Transfer, is a set of rules for designing consistent,
easy-to-use and maintainable web APIs.
JSON stands for JavaScript Object Notation; it provides a straightforward, human-
readable and portable mechanism for transporting data between two systems.
Apple supplies the JSONSerialization class to help convert your objects in
memory to JSON and vice-versa.

287.What problems does delegation solve?


Avoiding tight coupling of objects
Modifying behavior and appearance without the need to subclass objects
Allowing tasks to be handed off to any arbitrary object

288.What is the major purposes of Frameworks?


Frameworks have three major purposes:
Code encapsulation
Code modularity
Code reuse
You can share your framework with your other apps, team members, or the iOS
community. When combined with Swift’s access control, frameworks help define
strong, testable interfaces between code modules.

289.Explain Swift Package Manager


The Swift Package Manager will help to vastly improve the Swift ecosystem,
making Swift much easier to use and deploy on platforms without Xcode such as
Linux. The Swift Package Manager also addresses the problem of dependency hell
that can happen when using many interdependent libraries.
The Swift Package Manager only supports using the master branch. Swift Package
Manager now supports packages with Swift, C, C++ and Objective-C.

290. Explain SiriKit Limitations


SiriKit cannot use all app types
Not a substitute for a full app only an extension
Siri requires a consistent Internet connection to work
Siri service needs to communicate Apple Servers.

291.Explain View Controller Lifecycle events order ?


There are a few different lifecycle event
- loadView
Creates the view that the controller manages. It’s only called when the view
controller is created and only when done programatically.
- viewDidLoad
Called after the controller’s view is loaded into memory. It’s only called when the
view is created.
- viewWillAppear
It’s called whenever the view is presented on the screen. In this step the view has
bounds defined but the orientation is not applied.
- viewWillLayoutSubviews
Called to notify the view controller that its view is about to layout its subviews.
This method is called every time the frame changes
- viewDidLayoutSubviews
Called to notify the view controller that its view has just laid out its subviews.
Make additional changes here after the view lays out its subviews.
- viewDidAppear
Notifies the view controller that its view was added to a view hierarchy.
- viewWillDisappear
Before the transition to the next view controller happens and the origin view
controller gets removed from screen, this method gets called.
- viewDidDisappear
After a view controller gets removed from the screen, this method gets called. You
usually override this method to stop tasks that are should not run while a view
controller is not on screen.
292.What is the difference between LLVM and Clang?
Clang is the front end of LLVM tool chain ( “clang” C Language Family Frontend
for LLVM ). Every Compiler has three parts .
1. Front end ( lexical analysis, parsing )
2. Optimizer ( Optimizing abstract syntax tree )
3. Back end ( machine code generation )
Front end ( Clang ) takes the source code and generates abstract syntax tree
( LLVM IR ).

293.When and why do we use an object as opposed to a struct?


Structs are value types. Classes(Objects) are reference types.

294.What is UIStackView?
UIStackView provides a way to layout a series of views horizontally or vertically.
We can define how the contained views adjust themselves to the available space.

295.What are the most important application delegate methods a developer


should handle ?
The operating system calls specific methods within the application delegate to
facilitate transitioning to and from various states. The seven most important
application delegate methods a developer should handle are:
application:willFinishLaunchingWithOptions
Method called when the launch process is initiated. This is the first opportunity to
execute any code within the app.
application:didFinishLaunchingWithOptions
Method called when the launch process is nearly complete. Since this method is
called is before any of the app’s windows are displayed, it is the last opportunity to
prepare the interface and make any final adjustments.
applicationDidBecomeActive
Once the application has become active, the application delegate will receive a
callback notification message via the method applicationDidBecomeActive.
This method is also called each time the app returns to an active state from a
previous switch to inactive from a resulting phone call or SMS.
applicationWillResignActive
There are several conditions that will spawn the applicationWillResignActive
method. Each time a temporary event, such as a phone call, happens this method
gets called. It is also important to note that “quitting” an iOS app does not
terminate the processes, but rather moves the app to the background.
applicationDidEnterBackground
This method is called when an iOS app is running, but no longer in the foreground.
In other words, the user interface is not currently being displayed. According to
Apple’s UIApplicationDelegate Protocol Reference, the app has approximately
five seconds to perform tasks and return. If the method does not return within five
seconds, the application is terminated.
applicationWillEnterForeground
This method is called as an app is preparing to move from the background to the
foreground. The app, however, is not moved into an active state without the
applicationDidBecomeActive method being called. This method gives a developer
the opportunity to re-establish the settings of the previous running state before the
app becomes active.
applicationWillTerminate
This method notifies your application delegate when a termination event has been
triggered. Hitting the home button no longer quits the application. Force quitting
the iOS app, or shutting down the device triggers the applicationWillTerminate
method. This is the opportunity to save the application configuration, settings, and
user preferences.

296.What does code signing do?


Signing our app allows iOS to identify who signed our app and to verify that our
app hasn’t been modified since you signed it. The Signing Identity consists of a
public-private key pair that Apple creates for us.

297.What is the difference between property and instance variable?


A property is a more abstract concept. An instance variable is literally just a
storage slot, like a slot in a struct. Normally other objects are never supposed to
access them directly. Usually a property will return or set an instance variable, but
it could use data from several or none at all.

298.What is Downcasting ?
When we’re casting an object to another type in Objective-C, it’s pretty simple
since there’s only one way to do it. In Swift, though, there are two ways to cast — 
one that’s safe and one that’s not .
as used for upcasting and type casting to bridged type
as? used for safe casting, return nil if failed
as! used to force casting, crash if failed. should only be used when we know
the downcast will succeed.

299.Why is everything in a do-catch block?


In Swift, errors are thrown and handled inside of do-catch blocks.

300. What is your favorite app and why ?

301.What kind of JSONSerialization have ReadingOptions ?


mutableContainers Specifies that arrays and dictionaries are created as
variables objects, not constants.
mutableLeaves Specifies that leaf strings in the JSON object graph are
created as instances of variable String.
allowFragments Specifies that the parser should allow top-level objects that
are not an instance of Array or Dictionary.

302.Explain subscripts ?
Classes, structures, and enumerations can define subscripts, which are shortcuts
for accessing the member elements of a collection, list, or sequence.

303.What is the difference ANY and ANYOBJECT ?


According to Apple’s Swift documentation:
Any can represent an instance of any type at all, including function types
and optional types.
AnyObject can represent an instance of any class type.

304. When do you use optional chaining vs. if let or guard ?


We use optional chaining when we do not really care if the operation fails;
otherwise, we use if let or guard. This answer comes straight from the Expanded
Edition of Parsing JSON in Swift.
Using the question mark operator like this is called optional chaining. Apple’s
documentation explains it like this:
Optional chaining is a process for querying and calling properties, methods, and
subscripts on an optional that might currently be nil. If the optional contains a
value, the property, method, or subscript call succeeds; if the optional is nil, the
property, method, or subscript call returns nil. Multiple queries can be chained
together, and the entire chain fails gracefully if any link in the chain is nil.

305.How many different ways to pass data in Swift ?


There are many different ways such as Delegate, KVO, Segue, and
NSNotification, Target-Action, Callbacks.

306.Explain to using Class and Inheritance benefits


With Overriding provides a mechanism for customization
Reuse implementation
Subclassing provides reuse interface
Modularity
Subclasses provide dynamic dispatch

307.Explain AutoLayout
AutoLayout provides a flexible and powerful layout system that describes how
views and the UI controls calculates the size and position in the hierarchy.

308. What is the disadvantage to hard-coding log statements ?


First, when you start to log. This starts to accumulate. It may not seem like a lot,
but every minute adds up. By the end of a project, those stray minutes will equal to
hours.
Second, Each time we add one to the code base, we take a risk of injecting new
bugs into our code.

309. What is Pointer ?


A pointer is a direct reference to a memory address. Whereas a variable acts as a
transparent container for a value, pointers remove a layer of abstraction and let you
see how that value is stored.

310.What is pair programming?


Pair programming is a tool to share information with junior developers. Junior and
senior developer sitting side-by-side this is the best way for the junior to learn
from senior developers.
Check out Martin Fowler on “Pair Programming Misconceptions”, WikiHow on
Pair Programming

311. What is Keychain ?


Keychain is an API for persisting data securly in iOS App.

312.What is the biggest changes in UserNotifications ?


We can add audio, video and images.
We can create custom interfaces for notifications.
We can manage notifications with interfaces in the notification center.
New Notification extensions allow us to manage remote notification
payloads before they’re delivered.

313.How could we get device token ?


There are two steps to get device token. First, we must show the user’s permission
screen, after we can register for remote notifications. If these steps go well, the
system will provide device token. If we uninstall or reinstall the app, the device
token would change.

314.What is Encapsulation ?
Encapsulation is an object-oriented design principles and hides the internal states
and functionality of objects. That means objects keep their state information
private.

315.What is three triggers for a local notification ?


Location, Calendar, and Time Interval. A Location notification fires when the GPS
on your phone is at a location or geographic region. Calendar trigger is based on
calendar data broken into date components. Time Interval is a count of seconds
until the timer goes off.

316.What is Remote Notifications attacment’s limits ?


We can be sent with video or image with push notification. But maximum payload
is 4kb. If we want to sent high quality attachment, we should use Notification
Service Extension.

317.Explain unwind segue


An unwind segue moves backward through one or more segues to return the user
to a scene managed by an existing view controller.
318.What’s the difference between Android and iOS designs?
Android uses icons, iOS mostly uses text as their action button. When we
finish an action, on Android you will see a checkmark icon, whereas on iOS
you’ll have a ‘Done’ or ‘Submit’ text at the top.
iOS uses subtle gradients, Android uses flat colors and use different tone/
shades to create dimension. iOS uses bright, vivid colors — almost neon like.
Android is colorful, but not as vivid.
iOS design is mostly flat, but Android’s design is more dimensional.
Android adds depth to their design with floating buttons, cards and so on.
iOS menu is at the bottom, Android at the top. Also a side menu/hamburger
menu is typically Android. iOS usually has a tab called ‘More’ with a
hamburger icon, and that’s usually the menu & settings rolled into one.
Android ellipsis icon (…) to show more options is vertical, iOS is
horizontal.
Android uses Roboto and iOS uses San Francisco font
Frosted glass effect used to be exclusive to iOS, but you’ll see a lot of them
in Android too nowadays. As far as I know it’s still a hard effect to replicate
in Android.
Android usually has navigation button in color, whereas iOS is usually
either white or gray.

319. What is Webhooks ?


Webhooks allow external services to be notified when certain events happen
within your repository. (push, pull-request, fork)

320.What is Instruments?
Instrument is a powerful performance tuning tool to analyze that performance,
memory footprint, smooth animation, energy usage, leaks and file/network
activity.

321.What is Deep Linking?


Deep linking is a way to pass data to your application from any platform like,
website or any other application. By tapping once on link, you can pass necessary
data to your application.

322. Explain super keyword in child class


We use the super keyword to call the parent class initializer after setting the child
class stored property.

323. Explain In-app Purchase products and subscriptions


Consumable products: can be purchased more than once and used items
would have to re-purchase.
Non-consumable products: user would be able to restore this functionality in
the future, should they need to reinstall the app for any reason. We can also
add subscriptions to our app.
Non-Renewing Subscription: Used for a certain amount of time and certain
content.
Auto-Renewing Subscription: Used for recurring monthly subscriptions.

324.What is HealthKit ?
HealthKit is a framework on iOS. It stores health and fitness data in a central
location. It takes in data from multiple sources, which could be different devices. It
allows users to control access to their data and maintains privacy of user data. Data
is synced between your phone and your watch.

325. Explain Neural networks with Core ML


Neural networks and deep learning currently provide the best solutions to many
problems in image recognition, speech recognition, and natural language
processing.
Core ML is an iOS framework comes with iOS 11, helps to process models in your
apps for face detection. For more information follow this guideline https://
developer.apple.com/machine-learning/

326.Explain libssl_iOS and libcrypto_iOS


These files are going to help us with on device verification of our receipt
verification files with In-App purchases.

327.Explain JSONEncoder and JSONDecoder in Swift4


JSONEncoder and JSONDecoder classes which can easily convert an object to
encoded JSON representation.

328.What is NotificationCenter ?
NotificationCenter is an observer pattern, The NSNotificationCenter singleton
allows us to broadcast information using an object called NSNotification.
The biggest difference between KVO and NotificationCenter is that KVOtracks
specific changes to an object, while NotificationCenter is used to track generic
events.

329.Why is inheritance bad in swift?


We cannot use superclasses or inheritance with Swift value types.
Upfront modelling
Customization for inheritance is an imprecise

330. What kind of benefits does Xcode server have for developers?
Xcode server will automatically check out our project, build the app, run tests, and
archive the app for distribution.

331.What is Xcode Bot?


Xcode Server uses bots to automatically build your projects. A bot represents a
single remote repository, project, and scheme. We can also control the build
configuration the bot uses and choose which devices and simulators the bot will
use.

332.What is an “app ID” and a “bundle ID” ?


A bundle ID is the identifier of a single app. For example, if your organization’s
domain is xxx.com and you create an app named Facebook, you could assign the
string com.xxx.facebook as our app’s bundle ID.
An App ID is a two-part string used to identify one or more apps from a single
development team. You need Apple Developer account for an App ID.

333.What are layer objects?


Layer objects are data objects which represent visual content and are used by
views to render their content. Custom layer objects can also be added to the
interface to implement complex animations and other types of sophisticated visual
effects.

334.Explain Property Observer


A property observer observes and responds to changes in a property’s value. With
property observer, we don’t need to reset the controls, every time attributes
change.

335.Why do you generally create a weak reference when using self in a block?
To avoid retain cycles and memory leaks.

336.What are some ways to support newer API methods or classes while
maintaining backward compatibility?
For instance, if you want your view to have a red tintColor (a method introduced
in iOS 7), but your app still supports iOS 6, how could you make sure it won’t
crash when running on iOS 6? Another example would be using NSURLSession
vs. NSURLConnection — how could you make it so that your code uses the most
appropriate of those two classes?
Treat deprecated APIs warnings as errors to resolve.
At runtime, check for OS versions.
objC : Mark legacy code paths with macros.
if #available(iOS 8, *, *) {
self.view.convertPoint(.Zero, toCoordinateSpace:anotherView)
} else {
self.view.convertPoint(CGPointZero, toView:anotherView)
}
Control the number of 3d party libraries.

337.Which is faster: for a search an NSArray or an NSSet?


When the order of the items in the collection is not important, NSSet offers better
performance for finding items in the collection; the reason is that the NSSet uses
hash values to find items (like a dictionary), while an array has to iterate over its
entire contents to find a particular object.

338.Consider the following code:


var defaults = NSUserDefaults.standardUserDefaults()
var userPref = defaults.stringForKey("userPref")!
printString(userPref)
func printString(string: String) {
println(string)
}
Where is the bug? What does this bug cause? What’s the proper way to fix it?
Answer: The second line uses the stringForKey method of NSUserDefaults, which
returns an optional, to account for the key not being found, or for the
corresponding value not being convertible to a string.
During its execution, if the key is found and the corresponding value is a string,
the above code works correctly. But if the key doesn’t exist, or the corresponding
value is not a string, the app crashes with the following error:
fatal error: unexpectedly found nil while unwrapping an Optional value
The reason is that the forced unwrapping operator ! is attempting to force unwrap a
value from a nil optional. The forced unwrapping operator should be used only
when an optional is known to contain a non-nil value.
The solution consists of making sure that the optional is not nil before force-
unwrapping it:
let userPref = defaults.stringForKey("userPref")
if userPref != nil {
printString(userPref!)
}
An even better way is by using optional binding:
if let userPref = defaults.stringForKey("userPref") {
printString(userPref)
}

339.The following code snippet results in a compile time error:


struct IntStack {
var items = [Int]()
func add(x: Int) {
items.append(x) // Compile time error here.
}
}
Explain why a compile time error occurs. How can you fix it?
Answer: Structures are value types. By default, the properties of a value type
cannot be modified from within its instance methods.
However, you can optionally allow such modification to occur by declaring the
instance methods as ‘mutating’; e.g.:
struct IntStack {
var items = [Int]()
mutating func add(x: Int) {
items.append(x) // All good!
}
}

340.How to convert Swift String into an Array?


let Ustring : String = "iOS Developer Questions"
let characters = Array(Ustring.characters)
print(characters)

341.How to convert an array of Strings into a string in Swift using separator?



let SwiftStringsArray = ["iPhone","iPad","iPod"]
let MySwiftString = SwiftStringsArray.joinWithSeparator(",")
print(MySwiftString)

342.Would you consider yourself a Swift expert?


This is a trick question. Because Swift is still being improved, the only true “Swift
Experts” are the people who developed it at Apple. Even if you’ve produced lots
of great apps and mastered a number of advanced courses and tutorials, you simply
can’t be an expert at this point. Remember, Swift has only been around from
sometime. If your interviewer asks this, argue that you could not possibly be an
expert until the language is finished. Explain how you, like most other iOS
Developers, are constantly learning.

343.Consider the following code:


var array1 = [1, 2, 3, 4, 5]
var array2 = array1
array2.append(6)
var len = array1.count
What’s the value of the len variable, and why?
Answer:The len variable is equal to 5, meaning that array1 has 5 elements,
whereas array2 has 6 elements:
array1 = [1, 2, 3, 4, 5]
array2 = [1, 2, 3, 4, 5, 6]
When array1 is assigned to array2, a copy of array1 is actually created and
assigned.
The reason is that swift arrays are value types (implemented as structs) and not
reference types (i.e. classes). When a value type is assigned to a variable, passed as
argument to a function or method, or otherwise moved around, a copy of it is
actually created and assigned or passed. Note that swift dictionaries are also value
types, implemented as structs.
Value types in swift are:
• structs (incl. arrays and dictionaries)
• enumerations
• basic data types (boolean, integer, float, etc.)

344.Consider the following code:


let op1: Int = 1
let op2: UInt = 2
let op3: Double = 3.34
var result = op1 + op2 + op3
Where is the error and why? How can it be fixed?
Answer: Swift doesn’t define any implicit cast between data types, even if they are
conceptually almost identical (like UInt and Int).
To fix the error, rather than casting, an explicit conversion is required. In the
sample code, all expression operands must be converted to a common same type,
which in this case is Double:
var result = Double(op1) + Double(op2) + op3

345.Swift defines the AnyObject type alias to represent instances of any


reference type, and it’s internally defined as a protocol.
Consider the following code:
var array = [AnyObject]()
struct Test {}
array.append(Test())
This code generates a compilation error, with the following error message:
Type 'Test' does not conform to protocol 'AnyObject'
The failure is obvious because a struct is a value and not a reference type, and as
such it doesn’t implement and cannot be cast to the AnyObject protocol.
Now consider the following code:
var array = [AnyObject]()
array.append(1)
array.append(2.0)
array.append("3")
array.append([4, 5, 6])
array.append([7: "7", 8: "8"])

struct Test {}
array.append(Test())
The array array is filled in with values of type respectively int, double, string,
array and dictionary. All of them are value types and not reference types, and in all
cases no error is reported by the compiler. Why?
Answer: The reason is that swift automatically bridges:
• number types to NSNumber
• strings to NSString
• arrays to NSArray
• dictionaries to NSDictionary
which are all reference types.

346. Should I learn Swift or Objective-C?


Swift! Apple has made it clear that Swift is the cornerstone of the future of iOS
development. Plus, you can still utilize Objective-C files alongside Swift code, so
you won’t miss out on any pre-existing libraries and code.

347. Swift Is it fast?


Apple boasts that Swift is up to 2.6x faster than Objective-C and 8.4x faster than
Python 2.7. And why should you care about how quickly code executes? Well,
faster running code makes for more efficient and smoother running apps, which
makes for a better experience for your user.

348. Why did Apple decide to create a new language?


Objective-C has been Apple’s primary programming language for app writing
since OS X was created. In that time, programming languages and practices
changed drastically, especially in mobile development. Rather than adopt a new,
already existing language, Apple created a new language tailored specifically for
development on their own hardware.

349. What other languages is it similar to?


Swift is probably most similar in look and feel to Ruby or Python. Though you’ll
also probably recognize some C syntax.

350.MVVM
This MVVM tutorial takes a look at a different pattern for structuring applications,
Model-View-ViewModel, or MVVM. This pattern, facilitated by ReactiveCocoa,
provides an excellent alternative to MVC, and guarantees sleek and lightweight view
controllers!
The Model-View-ViewModel, or MVVM pattern as it’s commonly known, is a UI design
pattern. It’s a member of a larger family of patterns collectively known as MV*, these
include Model View Controller (MVC), Model View Presenter (MVP) and a number of
others.
Each of these patterns is concerned with separating UI logic from business logic in order
to make applications easier to develop and test.
More recently Martin Fowler introduced a variation of the MVC pattern termed the
Presentation Model, which was adopted and popularized by Microsoft under the name
MVVM.

At the core of this pattern is the ViewModel, which is a special type of model that
represents the UI state of the application.
It contains properties that detail the state of each and every UI control. For example, the
current text for a text field, or whether a specific button is enabled. It also exposes the
actions the view can perform, like button taps or gestures.
It can help to think of the ViewModel as the model-of-the-view.
The relationships between the three components of the MVVM pattern are simpler than
the MVC equivalents, following these strict rules:
1 The View has a reference to the ViewModel, but not vice-versa.
2 The ViewModel has a reference to the Model, but not vice-versa.
If you break either of these rules, you’re doing MVVM wrong!
A couple of immediate advantages of this pattern are as follows:
1 Lightweight Views – All your UI logic resides within the ViewModel, resulting in
a very lightweight view.
2 Testing – you should be able to run your entire application without the View,
greatly enhancing its testability.
At this point, you might have spotted a problem. If the View has a reference to the
ViewModel but not vice-versa, how does the ViewModel update the View?
Unfortunately, iOS lacks a data-binding framework, but this is where ReactiveCocoa acts
as the ‘glue’ that connects the ViewModel together.
Looking at the MVVM pattern specifically from the perspective of iOS development, the
ViewController and its associated UI — whether that is a nib, storyboard or constructed
though code — composes the View:

…with ReactiveCocoa binding the two together.


The MVVM pattern relies on data-binding, a framework level feature that automatically
connects object properties to UI controls.
As an example, within Microsoft’s WPF framework, the following markup binds the Text
property of a TextField to the Username property on the ViewModel:
<TextField Text=”{DataBinding Path=Username, Mode=TwoWay}”/>
The WPF framework ‘binds’ these two properties together.
The TwoWay binding ensures that changes to the ViewModel’s Username property
propagate to the Text property of the TextField, and vice-versa, i.e. user-input is reflected
in the ViewModel.
As another example, with the popular web-based MVVM framework Knockout, you can
see the same the same binding feature in action:
<input data-bind=”value: username”/>
The above binds a property of an HTML element with a JavaScript model.

351.Features of iOS 10:


1 The SiriKit :

◦ Applications which will be service providers in particular domains can use


this feature help people avail the services using Siri itself
◦ The SiriKit specifies an interactive object that links an intent to the
information regarding the process of intent-handling, which includes
details like the time of start and the complete duration of an occurring
process
◦ All user interactions are handled by Siri, but with the use of extensions,
you are able to provide custom UI which can consolidate other information
from the app
◦ Intents are the application extension which handles Siri related requests
2 Proactive suggestions:
◦ For iOS 10 along with future versions, it will be easier to give information
regarding the actions of the users in the application. Thus, it will help the
system in promoting your application in others places, like the keyboard
having QuickType suggestions, the application switcher, interactions with
Siri, Maps and the device’s lock screen
◦ These utilities for system’s improved integration get their support by a
number of technologies, such as web markup that is defined by
Schema.org, NSUserActivity and APIs in the UIKit, Core Spotlight,
MapKit and other Media Player frameworks
3 Enhancements in App search :
◦ In iOS 9, search APIs such as Core Spotlight, NSUserActivity and web
markup lets users search content by Safari and Spotlight search interfaces.
In iOS 10, you will get to use new Core Spotlight symbols to let users
continue a search they began in Spotlight when they open your app
◦ Deep linking.
4 Sticker pack:

This enables to add normal images or animated images into an app. These images
can be shared using the Message app.
5 CallKit :
Utilize this system to give users an opportunity to view and answer incoming VoIP
calls with the lock screen and maintain contacts from VoIP calls in the Phone
application’s Favorites and Recents views.
6 Account for the Video Subscriber:
This will enable applications that would support verified streaming or verified
video on demand to validate with the television provider. By the use of APIs
within this framework will help support a single sign-in experience. This will help
users sign-in only once to access the videos and other subscriptions.
7 The support of 3D Touch:
◦ Equipped to expand notifications.
◦ Provision of shortcuts to applications.
◦ In app actions

8 Recognition of Speech :
The iOS 10 is capable of supporting speech recognition and thus helps in building
applications which are able to recognize and transcribe the speech into text.
9 Security:
◦ The RC4 symmetric cipher suite is disabled by default for all SSL/TLS
connections, and SSLv3 is not supported in the Secure Transports API. It is
recommended to stop using the SHA-1 and 3DES cryptographic algorithms
◦ The SecKey API includes improvements for an asymmetric key generation.
You should use the SecKey API instead of the deprecated Common Data
Security Architecture (CDSA) APIs.
10 Application extensions:
◦ Home: It is provided with lock screen widgets.
◦ iMessage extensions are able to share app content from the message app
like Sticker packs.
◦ Intents – In order to handle Siri requests.
◦ Expanded notifications are available using 3D touch and the detailed view.
◦ The Call directory: The CallKit framework has been introduced with
application extensions that help in blocking calls and identify callers.
However, the Call Directory application extensions cannot be launched
during incoming calls and an application extension cannot retrieve the
phone number for an incoming call.
11 Notification enhancements:
◦ Media can be attached in the form of normal images, GIFs, audio and even
video URLs.
◦ The 3D touch allows users to expand their view thus it being in detail and
larger than usual.
◦ Notification service/content extension – the size is limited to 4KB, so you
can attach video URL and this extension allows to download a file without
opening the app.
12 Added User Notifications Framework
13 iOS 10 Deprecated API’s:
◦ CloudKit APIs
◦ Several Notification Classes
Although iOS 10 is reported to have some minor bugs yet it is a promising update for
Apple users that gives you an enjoyable experience.

352.iOS 11: All the new features


Hidden features galore. Apple didn't announce every single feature added to iOS 11 at
its big event at WWDC in June (above). That's OK -- we started digging through it a
short time later. Here,
Slight tweaks to Messages. A new iMessage app drawer, a new Apple Pay app, and a
couple of screen effects have been added to the app.
Notification Center is dead, long live Cover Sheet. The central hub on iOS 11 where
you can find all of your alerts and notifications is now called Cover Sheet. Not only does
it look different, but it has a few new quirks to it as well.
Drastic changes are coming. At first glance, it's going to seem like Apple didn't change a
lot when it comes to the look and feel of iOS 11 -- but it did. In fact, there are
Text with Siri. It's not always possible to have a voice conversation with Siri. While it
was added as an accessibility feature, the ability to
Keep your location private. With iOS 11, you now have the control of just how often an
app can access your location information -- regardless of what options the developer has
added to the app. You'll be prompted the first time you launch an app that always tracks
you, and presented with an
Forget your Wi-Fi's password. The next time a friend wants to connect to your Wi-Fi
network, you can approve the request directly on your iOS 11 device without having to
remember or hand over the password. Forget app passwords, too. Apple has expanded its
iCloud Keychain password manager beyond Safari. Now, you can use it to log into Take
control
Make Control Center your own. The three-panel Control Center from iOS 10 is gone.
With iOS 11 you can add or remove shortcuts you don't use, along with a few
AirPods get smarter. Instead of the lone option to activate Siri with a double-tap on
either AirPod earbud, starting with iOS 11 you can
Free up storage space. Storage space on a mobile device is always at a premium,
especially if you're using a 16GB phone. Apple is making iOS smart enough to
proactively get rid of unused apps, and providing tips to free up space with a tap.
Stay safe while driving. Your iPhone can now tell when you're in a car, and in turn it
will automatically enable a new feautre called Do Not Disturb While Driving. Any
incoming text alerts will be stopped, keeping your eyes on the road.
Go dark. There's a new dark mode hidden in the Settings app for iOS users. It's not
designed for daily use, but it can come in handy in dark environments.
Get creative
Live Photos get lively. Creating a quick animation out of a Live Photo is now possible
with a couple of taps. The end result is fun,
Screenshots on steroids. A new screenshot tool in iOS 11 makes it easy to capture
what's on your screen, edit, crop or add your signature and then share it and delete it.
But screenshots are so 2016. With a quick tap of a button, you can now record your iOS
device's screen. This is particularly handy for creating how-to guides -- perhaps you want
to show off how to beat the last level of Monument Valley 2. What are you waiting for?
Scan documents in the Notes app. Yup, Apple added a document scanner to the Notes
app on iOS 11. Launch the app, select scan document.
353.why swift is protocol oriented language
This design approach works, but does come with some drawbacks. For example, if you
add the ability to create machines that also require gas, birds that fly in the background,
or anything else that may want to share game logic, there isn’t a good way to separate the
functional components of vehicles into something reusable.
This scenario is where protocols really shine.
Swift has always let you specify interface guarantees on existing class, struct and enum
types using protocols. This lets you interact with them generically. Swift 2 introduced a
way to extend protocols and provide default implementations. Finally, Swift 3 improves
operator conformance and uses these improvements for the new numeric protocols in the
standard library.
Protocol are extremely powerful and can transform the way you write code. In this
tutorial, you’ll explore the ways you can create and use protocols, as well as use
protocol-oriented programming patterns to make your code more extensible.
You’ll also see how the Swift team was able to use protocol extensions to improve the
Swift standard library itself, and how it impacts the code you write.
Before we start writing code, lets create a class diagram that shows our design. I usually
start off by doing a very basic diagram that simply shows the classes themselves without
much detail. This helps me picture the class hierarchy in my mind. The following
diagram shows the class hierarchy for our Object-Oriented design:

This diagram shows that we have one superclass named Animal and two subclasses
named Alligator and Lion. We may think that, with the three categories, we would need
to create a larger class hierarchy where the middle layer would contain the classes for the
Land, Air and Sea animals however that is not possible with our requirements. The
reason this is not possible is because animal types can be members of multiple categories
and with a class hierarchy each class can have only one super class. This means that our
Animal super class will need to contain the code required for each of the three
categories. Lets take a look at the code for the Animal super class.
As we can see in these classes we override the functionality needed for each animal. The
Lion class contains the functionality for a land animal and the Alligator class contains the
functionality for both a land and sea animal. Since both class have the same Animal
superclass we can use polymorphism to access them through the interface provided by
the Animal superclass. Lets see how we would do this.
How we designed the animal types here would definitely work but there are several
drawbacks to this design. The first drawback is the large monolithic Animal superclass.
For those that are familiar with designed characters for video games you probably realize
how much functionality is actually missing form the Animal superclass and it’s
subclasses. This is on purpose so we can focus on the design and not all of the
functionality. For those who are not familiar with designed characters for video games,
trust me when I say that this class will get much bigger when we add all of the
functionality needed.
Another drawback is not being able to define constants in the superclass that the
subclasses can set. We could define an initiator in the superclass that would set all of the
constants however the initiator would become pretty complex and that is something we
would like to avoid. The builder pattern could help us with the initiation but as we are
about to see, a protocol-oriented design would be even better.
One final drawback that I am going to point out is the use of flags (landAnimal,
seaAnimal and airAnimal properties) to define the type of animal. If we accidently set
these flags wrong then the animal will not behave correctly. As an example, if we set the
seaAnimal flag rather than the landAnimal flag in the Lion class then the lion would not
be able to move or attack on land. Trust me it is very easy even for the most experience
developer to set flags like these wrong.
Now lets look at how we would define this same functionality in a Protocol-Oriented
way.
Protocol-Oriented Design
Just like with the Object-Oriented design, we will want to start off with a type diagram
that shows the types needed to create and the relationships between them. The following
diagram shows our Protocol-Oriented design.
As we can see our POP design is different from our OOP design. In this design we use
three techniques that make POP significantly different from OOP. These techniques are
protocol inheritance, protocol composition and protocol extensions.
Protocol inheritance is where one protocol can inherit the requirements from one or more
other protocols. In our example the LandAnimal, SeaAnimal and AirAnimal protocols
will inherit the requirements of the Animal protocol.
Protocol composition allows types to conform to more than one protocol. This is one of
the many advantages that POP has of OOP. With OOP a class can have only one
superclass which can lead to very monolithic superclasses as we just saw. With POP we
are encouraged to create multiple smaller protocols with very specific requirements.
Protocol extensions are arguably one of the most important parts of the protocol-oriented
programming paradigm. They allow us to add functionality to all types that conform to a
given protocol. Without protocol extensions if we had common functionality that was
needed for all types, that conformed to a particular protocol, then we would of had to add
that functionality to each type. This would lead to large amounts of duplicate code and
that would not be ideal to say the least.
Lets look at how this design works. We will start off by defining our Animal protocol.
Notice that we specify that the Lion type conforms to the LandAnimal protocol while the
Alligator type conforms to both the LandAnimal and SeaAnimal protocols. Having a
single type that conforms to multiple protocols is called protocol composition and is
what allows us to use smaller protocols rather than one giant monolithic superclass as in
the OOP example.
Both the Lion and Alligator types originate from the Animal protocol thereforel we can
still use polymorphism as we did in the OOP example where we use the Animal type to
store instances of the Lion and Alligator types. Lets see how this works:
seeing some of the advantages that protocol-oriented programming has over object-
oriented programming, we may think that protocol-oriented programming is clearly
superior to object-oriented programming. However, this assumption may not be totally
correct.
Object-oriented programming has been around since the 1970s and is a tried and true
programming paradigm. Protocol-oriented programming is the new kid on the block and
was designed to correct some of the issues with object-oriented programming. I have
personally used the protocol-oriented programming paradigm in a couple of projects and
I am very excited about its possibilities.
Object-oriented programming and protocol-oriented programming have similar
philosophies like creating custom types that model real-world objects and polymorphism
to use a single interface to interact with multiple types. The difference is how these
philosophies are implemented.
To me, the code base in a project that uses protocol-oriented programming is much safer
and easier to read and maintain as compared to a project that uses object-oriented
programming. This does not mean that I am going to stop using object-oriented
programming all together. I can still see plenty of need for class hierarchy and
inheritance.

354.zip in swift
You can use zip to combine your two arrays, and thereafter apply a .flatMap to the tuple
elements of the zip sequence:

355-How many bytes we can send to apple push notification server.

256bytes.

356.Explain Sqlite methods?

sqlite3_open

sqlite3_prepare_v2

sqlite3_step

sqlite3_finalize

sqlite3_close

SQLITE_OK

SQLITE_ROW

357. What is the base class for all the classes?

NSobject.
358. Default constructor syntax is?

- (id) init.

359. What is diff between Get and Post methods?

As per functionality both GET and POST methods were same.Difference is GET
method will be showing the information information to the users.But in the
case of POST method information will not be shown to the user.

The data passed using the GET method would be visible to the user of the website
in the browser address bar but when we pass the information using the
POST method the data is not visible to the user directly.

Also in GET method characters were restricted only to 256 characters.But in the
case of POST method characters were not restricted.

Get method will be visible to the user as it sended appended to the URL, put
Post will not be visible as it is sent encapsulated within the HTTP request
body.

About the data type that can be send, with Get method you can only use text as it
sent as a string appended with the URL, but with post is can text or binary.

About form default, Get is the defualt method for any form, if you need to use the
post method, you have to change the value of the attribute "method" to be
Post.

Get method has maximum length restricted to 256 characters as it is sent appended
with the URL, but the Post method hasn't.

Get method has limitataion in the size of data tranamitted, but post method hasn’t.

360. How to change the Application Name?

If you need to change the name of the Application as it appears on the iPhone's
home screen, you need to do it in the Target configuration, not the project
configuration. Expand the Targets group in Xcode, then single-click the item
under that. It should share the name of your project, which is also the default
name of the application that gets generated.

Press command-I to bring up the Info window, then navigate to the Build tag. Set
the Configuration drop-down to read All Configurations, then look for a
setting called Product Name under the Packaging heading. Change that
value to the name you want for your compiled applications and, in the
immortal words of Bugs Bunny: Viola! Do a clean then build and your
application will take on the new name.

361. Tell me difference between Iphone and Android ?

iPhone is Apple’s touch screen mobile phone (also known as a smart phone). Its
newest permutation, iPhone 3.0 4.0 offers a wider range of features than its
predecessors, and offers formidable competition on the market. The iPhone
offers an expansive Applications Store, full of features that users are able to
download for a fee, or gratis. This smart phone comes complete with a
comprehensive search feature, that seems far more sophisticated than its
competitors, including Spotlight search engine, and the ability to search
within mail, contacts, and the calendar.

The Android (also known as the Google G1) is Google’s first smart phone
controlled through an Android. This smart phone also comes with its share
of applications, though not contesting the Apple iPhone. The Android comes
complete with a pull down ‘window shade’ notification area, which makes
users privy to multiple alerts. Basically, any number of virtual alerts –
Twitter replies, missed calls, an upcoming appointment, etc.- can all be
drawn up at the same time using the drop down shade feature. On the
contrary, the iPhone offers a pop up screen when such alerts occur; forcing
the user to have to end whatever activity he or she is performing – including
a phone call.

As Apple controls all the hardware of its iPhone market, it can perform any
number of tasks to improve the use of the phone. Quite simply, this means
that the iPhone comes with standard accessory support. Google’s Android is
simply an operating system that, while able to run on multiple platforms,
doesn’t give the user access to any sort of complimentary support for any of
the accessories themselves. The Android, therefore, can run on a multitude
of handsets, all with differing configurations, making control difficult.

Though lacking in the proper control to give users accessory support, the Android
comes with comprehensive MMS support. There are also stellar background
processes; however, these processes tend to overexert the battery. Apple’s
iPhone comes with its own set of background processes that aren’t as
intense, therefore spare the battery a great deal of wear and tear.

Summary:

1. The Apple iPhone comes with an expansive set of applications, available for
free or for a small fee; the Google Android comes with a smaller package of
applications.

2. The Apple iPhone comes with a feature to alert the user of any missed
instances, though this feature forces the user to prematurely end whatever
action he is performing; the Google Android comes with a drag and drop
screen that alerts the user of any occurrences ,but allows him to continue his
actions.

3. Apple controls all of its hardware, and it is therefore simple to perform the
necessary accessory maintenance; Google’s Android is simply a platform
that functions on different platforms, and doesn’t allow for easy accessory
support.

362. What is Sandbox in iphone ?


Ans: The sandbox is a term used to describe the limited file system available to
each application.

Each app only has access to a few directories:

read-only access to the application bundle (a special type of directory) read-
write access to a documents directory and a temp directory.

Apps can't read or write to any other directories, either system directories or those
belonging to other apps.

Another way to think about it by pulling an analogy in is to think of an
actual sandbox at a park.

If kid A is playing in sandbox A, then anything in that space is available to them.


Kid B from sandbox B should not be able to interfere in any way with
sandbox A. Each is its own small environment.

In the real world the borders are physical, in the iphone, you have somewhat
of a physical partition between applications as they each get their own folder
structure, but its up to the OS to maintain the logical separation. Get
elevated privileges on the device and then the borders start to go away.

363. Differnce between NULL and Nil in Objective C ?

Ans: You can use nil about anywhere you can use null. The main difference is that
you can send messages to nil, so you can use it in some places where null
cant work.

They differ in their types. They're all zero, but NULL is a void *, nil is an id, and
Nil is a Class pointer.

364.Write code for BUTTON?

UIButton *b=[UIButton buttonWithType:UIButtonTypeRoundedRect];

[b setTitle:@“adding" forState:UIControlStateNormal];

b.frame=CGRectMake(10,420, 100,30 );

[b addTarget:self action:@selector(show)
forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:b];

365.Difference between Unlocking and jailbroking in iphone Explain its?

It lets you do everything from customizing the look of your iPhone to installing
third-party applications (such as titles that are not authorized and available
in the App Store) and customized ringtones on it. Depending on how far
you're willing to go, you can do even more than that: Jailbreaking even lets
you to unlock your phone so you can use it with a carrier other than the one
from which you purchased it.
Once you do it, you're on your own. You may have voided your warranty, so

you can't rely on AT&T, Verizon, or Apple to fix any problems you encounter. All
of the applications that jailbreak your phone are unauthorized and could
damage or completely disable your iPhone. Your slick smartphone could
end up as nothing more than a very expensive paperweight.

366. what is mean by App Thinning.

There are three main aspects of App Thinning: App Slicing, Bitcode, and On
Demand Resources. In this tutorial, we’ll explore each one of these.

App Slicing
The first aspect of App Thinning we will discuss is slicing. According to Apple,
“Slicing is the process of creating and delivering variants of the app bundle for
different target devices.
A variant contains only the executable architecture and resources that are needed
for the target device.” In other words, App Slicing delivers only relevant assets to
each device (depending on screen resolution, architecture, etc.) In fact, app slicing
handles the majority of the app thinning process.
When you’re ready to submit the app, you upload the .IPA or .App file to iTunes
Connect, as you typically would (but must use Xcode 7 as it contains the iOS 9
SDK with support for app thinning). The App Store then slices the app, creating
specific variants that are distributed to each device depending on its capabilities.

%
On Demand Resources
To fully comprehend and app thinning, it is imperative that you also understand
On Demand Resources (ODR). On demand resources are files that can be
downloaded after the app’s first installation. For example, specific levels of a
game (and these levels’ associated content) could be downloaded only when the
player has unlocked them. Further, earlier levels that the player has not engaged
with after a certain set time can be removed to save storage on the device.
Enabling on demand resources involves changing the “Enable On Demand
Resources” boolean to “Yes” in Xcode settings (under Build Settings).
%
Bitcode
The third and final aspect of App Thinning is bitcode. Bitcode is somewhat
abstract, but in essence, it is Apple’s new way of optimizing apps before they’re
downloaded. Bitcode makes apps as fast and efficient as possible on whatever
device they’re running. Bitcode automatically compiles the app for the most
recent compiler and optimizes it for specific architectures (i.e. arm64 for 64 bit
processors such as the iPhone 6s and iPad Air 2).
Bitcode makes downloads smaller by eliminating optimizations that are made for
different architectures and rather downloads only the relevant optimizations and
works hand in hand with the above mentioned app thinning technologies.
Bitcode is a newer feature to iOS, and needs to be turned on for newer projects.
This can be done via the the project settings under Build Settings and
selecting bitcode to YES.

%
App Thinning in Your Own Projects
Although Xcode and the App Store handles the majority of the App Thinning
process, there are certain precautions you must take to make sure your app works
with this new technology. First and foremost, you must use asset catalogs. Asset
catalogs are the default in most apps at this point. If you haven’t already adopted
Asset Catalogs, much of your existing content can be transferred over to a catalog
by pressing the “Use Asset Catalog” button under Xcode’s project settings as seen
below.
%
New to Xcode 7 are Sprite Atlases. Sprite Atlases are essentially a combination of
asset catalogs and the power of SpriteKit (Xcode’s technology for creating 2D
games). As such, if you’re using SpriteKit, this is a must for app thinning.
Testing with App Thinning
As you have seen from the above paragraphs, Xcode and Apple’s App Sore handle
much of the app thinning process, making it relatively easy to adopt this
technology into your own apps. But what if you want to test you app and ensure it
is ready for app thinning? Luckily, Apple’s TestFlight offers the perfect solution.
In addition to the App Store’s thinning technologies, TestFlight users can share in
the experience.
In this second half of the tutorial, we will explore how to work with App Thinning
in TestFlight.
To get started, download this (nearly) blank project, unzip it, and run it in Xcode.
You will notice there is essentially nothing in the project except several images in
the Asset Catalog (but not a lot of code). The Asset Catalog conains 1x, 2x, and 3x
versions of the app icon as well.

%
First, run the app on the simulator or a device. Open the settings app, click
“Storage & iCloud Usage” (or just “Storage” on non iOS 9 devices) and
select “Manage Storage”. Scroll down to the app we just compiled and tap it.
You’ll notice it is roughly 17.0 MB in size (this size may vary slightly when
uploaded to iTunes Connect).

%
When you build and run an app using Xcode, Xcode does not automatically handle
app variants and app thinning. As such, the entire app file is currently on your
device.
Next, click the Product tab from Xcode and select Archive.

%
Note: You will likely need to modify the App’s Bundle Identifier first to match one
that you created yourself. Otherwise, the app will not upload to iTunes Connect.

%
Make sure you select “Include bitcode” before pressing “Submit”. If everything
goes well, you’ll see a green checkmark informing you the build has been
uploaded.
Now sign in to iTunes Connect here, make a new app (include the proper bundle
ID, app name, etc.). If you’re unsure how to do this, please refer back to the
AppCoda TestFlight tutorial.

%
Add yourself as an internal tester. Be aware that it’s not uncommon to have a build
in the “Processing” state for several hours. Once the app is no longer processing,
select it and press the “Start Testing” button.
An email will be sent to the address you included. Make sure you are on the
proper iOS device you want to test on and accept the email. You’ll be brought to
the TestFlight app.

%
Install this build. Once it is installed, return to the settings app, navigate to
storage, and find the app as we did before. Notice that the app is now a mere 5.4
MB. That’s App Thinning at its prime!

%
Wow! You just shaved off 12.4 MB from your app – and this was a very basic app.
Apps that contain multiple different assets will see a even more dramatic change
in app size!
Summary
In this tutorial, we took a look at the power of app thinning. In so doing, we
discussed the three main aspects of app thinning: app slicing, on demand
resources, and bitcode.
Unfortunately, as of September 24 2015, Apple announced on its developer portal
that App Thinning has been delayed and is not included in the iOS 9 (or 9.0.1)
public launch:
“App slicing is currently unavailable for iOS 9 apps due to an issue affecting
iCloud backups created from iOS 9 where some apps from the App Store would
only restore to the same model of iOS device.
When a customer downloads your iOS 9 app, they will get the Universal version
of your app, rather than the variant specific for their device type. TestFlight will
continue to deliver variants for your internal testers. App slicing will be reenabled
with a future software update. No action is needed by you at this time.”
However, as I’ve included at the beginning of the article, app thinning has been
fixed and is ready for all devices running iOS 9.0.2. App thinning is an incredible
tool that will speed the way apps are downloaded forever!

367.WHAT’S NEW IN XCODE 9

Refactor
Finally! I’m not sure about you, but I was waiting for a long time for this! In the
new version, we are finally able to refactor our code. What can we change? We can
rename stuff, for example. Xcode is looking for the name to change in the whole
project.

%
It can also add missing required protocol methods, stubs or missing overrides.
%
We are able to convert if/else and switch statements. It’s also possible to extract
methods or local variables.
Wireless debugging
Another important piece of news is the inclusion of wireless debugging. It’s super
easy and works exactly as it should. I remember Apple tried to implement this in
the past but it was not working well and had been dropped in next update. We can
use WiFi for debugging iOS and tvOS devices. It’s necessary to plug-in our device
once, to enable network debugging, and then we are ready to go!
To enable it, just connect your device to your Mac and open the Devices section in
Xcode.

%
Now you are able to use wirelessly connected devices the same way as a wire
connection.
Simulators
In the new version, we also can run the app on multiple simulators at the same
time. We also can test syncing for multi-device workflows.

%
Main Thread Checker
A new feature called Main Thread Checker is able to verify if we are trying to call
AppKit, UIKit or WebKit methods, which aren’t from the main thread.
It’s enabled by default.
New templates
We also have new templates available for projects. Xcode is able to generate an
ARKit based app or Document Based App for us, for example. New templates are
also available for Playgrounds.

%
%
Improved editor
Also, the editor has been completely rebuilt. It looks a bit different than in the past.
We can easily use CMD + or – to increase or decrease font. Additionally, it has
better highlighting or navigation in code, also supporting Markdown. Searching
inside the project has also been improved and it now works much faster.

%
Source Control
Xcode now supports Github accounts. We can browse repositories, clone them,
push changes and manage branches.
Xcode Server built-in
There is no need for installing a macOS Server anymore. We are now able to run
an Xcode Server on our Mac, directly from Xcode.
Bot’s right now can run parallel tests on devices and a simulator, changing the
language and region for testing and sending email notifications.
XCTests
Xcode 9 brings us new functions for testing. The new API for XCTests allows us
to control and capture screenshots, using test attachments, target multiple apps in
one UI tests and also specifying the language and region.

368.In Swift, what are failable and throwing initializers?


Very often initialization depends on external data, this data can exist as it can not,
for that Swift provides two ways to deal with this.
Failable initializers return nil of there is no data, and let the developer “create” a
different path in the application based on that.
In other hand throwing initializers returns an error on initialization instead of
returning nil.

369.In Swift what are computed properties?


In addition to stored properties, classes, structures, and enumerations can define
computed properties, which do not actually store a value. Instead, they provide a
getter and an optional setter to retrieve and set other properties and values
indirectly.

370. What are tuples in Swift?


Tuples are simply ordered sets of values and for our purposes, they group multiple
values into a single compound value.
Why is this important? In Objective-C, if you want a method to return more than
one value you have two options — return a custom object with properties that store
your return values or stick those values in a dictionary. With Swift however, we
can use tuples to return more than one value. The values in a tuple can be of any
type and don’t have to be the same type as each other.
Tuples are value types. When you initialize a variable tuple with another one it
will actually create a copy.

371.What are generics in Swift?


Swift language provides ‘Generic’ features to write flexible and reusable functions
and types. Generics are used to avoid duplication and to provide abstraction. Swift
standard libraries are built with generics code. Swifts ‘Arrays’ and ‘Dictionary’
types belong to generic collections. With the help of arrays and dictionaries, the
arrays are defined to hold ‘Int’ values and ‘String’ values or any other types.
Generics are type safe, meaning if you pass a string as a generic and try to use
as a integer the compiler will complain and you will not be able to compile your.
Because Swift is using Static typing, and is able to give you a compiler error.
372.Property Observers
There are two very appropriately named property observers in Swift: willSet, and
didSet. They are called exactly when you think they would be, right before and
right after setting, respectively. On top of this, they are also implicitly given
constants describing the newValue and oldValue respectively.
• willSet comes with a constant parameter that contains the new value, with
the default name newValue
• didSet comes with a constant parameter that contains the old value, with the
default name oldValue
You can override either of those names, if you wish, but if no name is provided,
the defaults are used.

373.MVP vs MVC vs MVVM vs VIPER. What is Better for iOS


Development?

Same like every house has a solid basement, every software project, has an
software architecture it is built on, and each project has its own app structure. The
types of architectural patterns may vary, but there are 4 most commonly-used ones
- the ones whole IT world continuously criticizes but keeps using at the same time:
MVC, MVP, MVVM and Viper (the last one as iOS architecture pattern mostly).
The comparison of these patterns and choosing a better fit for each Swift-written
project’s case will be discovered further on in this article.
Following the chronological order of things, once the first software design patterns
have appeared, the common issues of those ios development architecture patterns
didn’t take long to arrive. For instance, the problem of server-client
communication - how does one interact with another? Or a different one - the
problem of separating the application’s business logic from the in-app’s logic; how
this one should perform in terms of application’s architecture? Due to them various
design patterns for different architecture layers have seen the world; the most well-
known amongst them are:
- Singleton design pattern.
This pattern allows one class to be applied to one object only, and this option is of
use when a limited amount of instances (or one instance only) is approved by the
system.
- Decorator design pattern.
In contrast to singleton, this pattern, (alternatively called Wrapper together with
the Adaptor pattern), lets a specific behavior to be added up to a single object
(either statically or dynamically), and all of this without affecting the behaviour of
other objects this one shares a class with.
- Bridge design pattern.
Firstly introduced by the notorious Gang of Four - authors of the book “Design
Patterns”, this architectural pattern “uses encapsulation, aggregation, and can use
inheritance to separate responsibilities into different classes.When a class aries
often, the features of object-oriented programming become very useful because
changes to a program's code can be made easily with minimal prior knowledge of
the program. [Source: Wiki]
Despite those patterns being pretty different, the common problems of code-
writers have occurred with each of them; for instance, with Singleton’s
“massivity”. Singleton is too global, as the dependencies of your code are hidden
deeply within your application, instead of being exposed in the interfaces. Which
is why during the software development process new patterns constantly appear.
The 4 most -commonly used patterns are MVC, MVP, MVVM and VIPER (for
iOS mainly).
Developed in the same order as listed, all of them have their own benefits and
flaws, causing numerous disputes about where to apply each one. Paying a bit
more attention to the best practises they implement might clear things up a bit.
1. MVC pattern
The grandfather of all the software patterns, first introduced in early 1970s by a
Norwegian computer scientist Trygve Reenskaug, Module - View - Controller,
widely-known as MVC, is one of the first pattern approaches of the Object -
Oriented Programming. The View part is responsible for displaying everything for
system’s user (interfaces of mobile or web app, etc.). Model is generally
responsible for the databases, business entities and rest of data. In its turn,
Controller regulates the Model’s work, data provided to the database, display from
the mentioned database to the View part and vice versa.
However universal the MVC model might be, the two biggest competitors - Apple
and Google have their own patterns representing Model - View - Controller
system. The issue Apple’s system has lies in the tight connection between View
and Controller parts, tight almost to the point of having united View & Controller,
and leaving Model part separated. Consequently, it results in poor testing process -
only Model could be examined, V&C (due to the tight connection they have) can
not be tested at all.
The robust connection between Controller and View segments proved to be truly
“unhealthy” when it comes to software, so a new pattern saw the world soon.
2. MVP pattern.
Many of us have heard this shortcut in the context of Minimum Viable Product,
but in terms of software engineering it means something different. The Model
View Presenter pattern has few key points, forming a vast gulf between it and
MVC:
MVP Model
• View is more loosely coupled to the model. The Presenter is responsible for
binding the Model to the View.
• Easier to unit test because interaction with the view is through an interface.
• Usually View to Presenter = map one-to-one. Complex views may have
multi presenters.
MVC Pattern
• Controllers are based on behaviors and can be shared across views
• Can be responsible for determining which view to display [Source:
Infragistics]
In this arrangement Model’s functions stay the same; Presenter is responsible for
the business logic respectively. The V part is the one of particular interest - as it is
divided into two parts View and View Controller, which are in authority for
interaction. When there is a MVVM vs MVC question, the system of this type
solves the problem of a “heavy addiction” View and Controller modes used to
have in MVC pattern.
The testing obstacle is also solved in this case, as Model, View with user
interaction, and Presenter parts - all of these could be tested.
The yet existing inconvenience is in Presenter’s part - yet way too massive, yet
takes into the account all of the existing business logics. Which is why the next act
came into play, named…
3. MVVM pattern

A Model-View-ViewModel software architectural pattern has been created in 2005


by John Gossman, one of Microsoft’s architects. The three core components of
MVVM model respectively are:
Model is “an implementation of the application's domain model that includes a
data model along with business and validation logic. Examples of model objects
include repositories, business objects, data transfer objects (DTOs), Plain Old CLR
Objects (POCOs), and generated entity and proxy objects.” [Source: Microsoft]
View is again everything that user is capable of seeing - the layout, the structure
and the appearance of everything on the screen. Basically, within the application it
would be app’s page. View gets and sends updates to ViewModel only, excluding
all the communication between this part and Model itself.
ViewModel is supposed to be an “interconnecting chain” between the View and
Model system components, and it’s main function is to handle the View’s logic.
Typically, the view model interacts with the model by invoking methods in the
model classes. The view model then provides data from the model in a form that
the view can easily use, as Microsoft states.
The main difference between MVC and iOS MVVM is that MVVM’s distribution
pattern is better than in the previously-listed MVC, but when compared to MVP it
is also massively overloaded. Testing is a matter of particular importance here, as
while plainly writing the code you can not guarantee that the whole project will
function properly - tests, on the bright note, help to ensure it will.
The next architectural patterns’ evolution has been recently released and is now the
freshest software architectural approach.
4. iOS VIPER architecture
Searching for the best architectural solution to deliver, iOS developers all over the
world bumped into a so-called “Clean Architecture” approach, introduced by
Uncle Bob on the Clean Coders - a well-known platform providing training
sessions for the software professionals worldwide. Clean Architecture splits the
application’s logical structure into several responsibility levels. In it’s turn, this
“separation” resolves the tight dependency issues and increases the testing
availability of all levels.
VIPER for ios development
VIPER is a realisation of Clean Architecture for iOS-built applications. As a
common rule for all the patterns’ names, it is a backronym as well, for View,
Interactor, Presenter, Entity and Routing. Each of the VIPER’s parts is responsible
for a certain element, particularly:
1) View is responsible for mirroring the actions user makes with an interface
2) Presenter’s responsibilities within the VIPER pattern are quite limited - it
receives the updates from Entity, but doesn’t send any data to it;
3) Interactor is the system’s part that actually corresponds with Entities. This
scheme works in the following direction: Presenter informs Interactor about the
changes in the View model, then Interactor contacts the Entity part, and, with the
data received from Entity Interactor gets back to Presenter, which commands View
to mirror it for a user. All the data models, all the entities and all the websites are
connected to the Interactor part.
4) Entity consists out of objects that are controlled by Interactor (titles, content.
etc.)It never interacts with Presenter directly, only via I-part.
5) Routing (or Wireframe as it is sometimes called) is responsible for navigation
between all of the screens, and, essentially, for routing. Wireframe controls the
objects of UIWindow, UINavigationController and so on. Particularly within iOS
architectural system it is all built upon a framework called UIkit, which includes
all the components of Apple MVC, but without a tight connection that used to
drive coders mad before.
VIPER module is as well beneficial once it comes to unit tests, as the great
pattern’s distribution lets you test all the functional available. In many ways this
was the main difficulty developers faced with previous MVC, MVP and MVVM
software patterns.
To Crown it All.
All of these 4 software design patterns are often called one of the best architecture
Patterns for iOS development, even though all of them are less than ideal and
definitely not universally used for each and every project you get to develop. On
the gloomy side, here is a short list of issues each pattern has:
• MVC, MVP, MVVM - all of them have this “tight connection” issue, which
makes introducing updates to development, and testing them afterwards
quite a harsh task to accomplish.
• VIPER vs MVVM, MVC or MVP, is thought to be a winning case; although
despite its high flexibility and great testability also has many nuances that
are hard to generate.

374.Dispatch Barriers and Dispatch group in Swift 3

Serial Queues

Tasks in serial queues execute one a time in first in first out format. Task1 has to
finish for Task2 to start. Task2 has to finish for Task3 to start and so on.

Concurrent Queues
Tasks in concurrent queues execute in any order and can start simultaneously.
Below code reads and writes to the dictionary concurrently. This is very fast
compared to the above serial queue. However, because we may be reading while
writing at the same time, we will run in to the readers-writers problem.
Using concurrent queues with barriers helps us improve and speed up our code
while eliminating the readers-writers problem, which is also important for
singletons.

Dispatch group
A dispatch group lets us easily keep track of multiple blocks that have been
dispatched to queues and be notified when they are complete. They make things
much simpler by allowing us to not need to keep state of all the blocks that we
have dispatched. Now it's not desperately complicated to do so, we could just keep
a count of how many blocks we have dispatched, or an array of the dispatched
blocks and decrement (or remove from the array) on completion. Since this is such
a common thing to do Apple have done this for is, it's worth noting that this can be
less simple to implement if we dispatch the same block multiple times, or are
dispatching blocks across several different queues.

375.What is the difference between rebase and merge in Git?

In terms of the end result (which is what matters, usually), after merging the end
result will look like the commits on both branches were made chronologically
"together", altering between the branches. After rebasing, the end result will look
like the branches were 'applied' separately, first one entire branch and then the
other.
The most important takeaway is that if branch (a) has a list of commits:
{a1, a2, a3, a4, a5} and branch (b) has a list of commits {b1, b2, b3, b4, b5}, then
after merging them the result might be something like:
> a1, b1, a2, a3, b3, b4, b5, a5 (mixed together),
while after rebasing (b) over (a) the list will necessarily look like:
> a1, a2, a3, a4, a5, b1, b2, b3, b4, b5. (one branch after the other)
If (b) is your feature branch and (a) is your stable master, this is much preferable
because logically you want all of (b)'s commits after (or in git-speak, 'rebased on')
the commit's on (a)'s.
Both Git merge and Git rebase are used to combine the work of two branches
together. Only the techniques of combining is different.
Consider an example to understand the difference between these two techniques:
Let's say that you have two branches in your Git repo viz. master and feature,
where the feature branch is being used to develop something additional & master
branch is your production quality code branch or main branch.
After you are done developing the feature branch, you want to combine it with the
master branch.
If you Git merge it into master, it will combine the tasks of feature into master by
creating a single new commit at the tip of master.
On the other hand, if you Git rebase it, it will place the entire commit history of
the feature branch on the tip of master. It means that your entire feature branch will
be reattached to the tip of master and it will look like a linear sequence of
commits.
However, there is a little rule to remember:
Combining tasks from public branch into local branch -- use git rebase
Combining tasks from local branch to public branch -- use git merge
Both Merge and Rebase have their pros and cons. Merge keeps the history of the
repository but can make it hard for someone to understand and follow what’s
going on at a particular stage when there are multiple merges. Rebase on the other
hand ‘rewrites’ history (read - creates new history) but makes the repo look cleaner
and is much easier to look at.
What you want to use depends on your need. A lot of companies make merges
mandatory when adding stuff to master branch because they want to see the history
of all changes. And a few companies/Open source projects mandate rebasing as it
keeps the flow simple and easy to follow. Use the one that suits your workflow.

376.What’s new in Swift 4.0

Migrating to Swift 4
Migration from one major version of Swift to the next one has always been pretty
intense, especially from Swift 2.x to 3.0. Usually it takes about 1-2 days per
project, but migration to Swift 4 is a bit easier and can be passed much faster.
Pre-migration preparation
Xcode 9 supports not only Swift 4, but a transitional version 3.2 as well, so your
project should compile without any harsh difficulties. This is possible because
Swift 4 compiler and migration tool support both versions of language. You can
specify different Swift versions per target, this is very helpful if some third-party
libraries didn't update yet or if you have multiple targets in your project. However,
not just language, but the SDK has got some changes too, so it's very likely that
some updates will have to be applied to your code as Apple continues to tide up
SDK APIs…

Swifty encoding and decoding


Swift 4 introduces a new Codable protocol that lets you serialize and deserialize
custom data types without writing any special code – and without having to worry
about losing your value types. Even better, you can choose how you want the data
to be serialized: you can use classic property list format or even JSON.
Yes, you read all that correctly: Swift 4 lets you serialize your custom data types to
JSON without writing any special code.

Access control
Swift 3 brought a very contradictory element to Access control - fileprivate access
modifier which can be really confusing.
Previously, private access level modifier was used to hide type members from
other types and private members could only be accessed by methods and
properties defined at type definition, leaving the same type extensions aside as
they couldn't access those members.
fileprivate could be used to share access for type members, such as properties and
methods, within the same file. In fact usage of private led to a problem when
extensions on some type didn't have access to members of that type, so using
fileprivate in under such circumstances was a very common solution, which has
led to another the problem: other types in the same file could access those
members too.
Swift 4 puts things in order by allowing extensions on the type to access private
members of that type in the same file

Subscript with default value


Previously, a common practice was to use the nil coalescing operator to give a
default value in case the value is nil.

Multi-line string literals


Writing multi-line strings in Swift has always meant adding \n inside your strings
to add line breaks wherever you want them. This doesn't look good in code, but at
least it displays correctly for users. Fortunately, Swift 4 introduces new multi-line
string literal syntax that lets you add line breaks freely and use quote marks
without escaping, while still benefiting from functionality like string interpolation.
To start a string literal, you need to write three double quotation marks: """ then
press return.
adds the ability to escape newlines in multi-line string literals with a backslash in
the end of the line.
Swift 4 brings support for Unicode 9 which means that problems with unicode
characters counting are now gone:

New Substring type


Swift 4 brings new Substring type which represents a subsequence of String
Both String and Substring now support new StringProtocol which makes them
almost identical and interoperable:

Improved keypaths for key-value coding


The Swift Evolution community spent quite a while discussing the correct syntax
for keypaths because it needed to be something visually different from other Swift
code, and the syntax they ended up with uses backslashes:
KVO
In addition to new key paths, key-value observing API has been updated in Swift 4
too.
New KVO APIs depend on Objective-C runtime and works for `NSObject`
subclasses only, so it can't be used for Swift structs and classes which don't inherit
`NSObject`. In order to observe property it should be marked as `@objc dynamic
var`.

Generic Subscripts
Subscripts can now have generic arguments and return types 🚀

Limiting Objective-C Inference


Swift 4 minimizes @objc inference by limiting it to only those cases when the
declaration has to be available for Objective-C.
This decreases your app's binary size by not compiling redundant Objective-C
code if you don't use it, and gives more control to when @objc will be inferred.
NSObject derived classes no longer infer @objc.
But there are some situations in which Swift code will continue to have an implicit
inference:
• Declarations that have an @objc attribute
• Declarations that satisfy a requirement of an @objc protocol
• Declarations that have @IBAction, @IBInspectable, @IBOutlet,
@NSManaged, @GKInspectable attributes
To enable @objc inference for an entire class you can use the new @objcmembers
attribute.
To disable @objc inference for a specific extension or function - add the new
@nonobjc attribute.

Composing Classes And Protocols


In Swift 4 we can now compose protocols together with other Swift types:

Improved dictionary functionality


One of the most intriguing proposals for Swift 4 was to add some new
functionality to dictionaries to make them more powerful, and also to make them
behave more like you would expect in certain situations.
Let's start with a simple example: filtering dictionaries in Swift 3 does not return a
new dictionary. Instead, it returns an array of tuples with key/value labels.

Strings are collections again!


This is a small change, but one guaranteed to make a lot of people happy: strings
are collections again. This means you can reverse them, loop over them character-
by-character, map() and flatMap() them, and more.

One-sided ranges
Last but not least, Swift 4 introduces Python-like one-sided collection slicing,
where the missing side is automatically inferred to be the start or end of the
collection. This has no effect on existing code because it's a new use for the
existing operator, so you don't need to worry about potential breakage.

377.What is the biggest difference between NSURLConnection and


NSURLSession

In an application we usually works with


1 Data tasks – Data tasks are used for requesting data from a server, such as
JSON data. These data are usually stored in memory and never touches the
File System We can use NSURLSessionDataTask.
2 Upload Tasks – Upload tasks are used to upload data to a remote
destination. We can use NSURLSessionUploadTask.
3 Download Tasks – Downloading a file and Storing in a temporary location.
We can use NSURLSessionDownloadTask.
The entire model is different. NSURLSession is designed around the assumption
that you'll have a lot of requests that need similar configuration (standard sets of
headers, etc.), and makes life much easier if you do.
NSURLSession also provides support for background downloads, which make it
possible to continue downloading resources while your app isn't running (or when
it is in the background on iOS). For some use cases, this is also a major win.
NSURLSession also provides grouping of related requests, making it easy to
cancel all of the requests associated with a particular work unit, such as canceling
all loads associated with loading a web page when the user closes the window or
tab.
NSURLSession also provides nicer interfaces for requesting data using blocks, in
that it allows you to combine them with delegate methods for doing custom
authentication handling, redirect handling, etc., whereas with NSURLConnection,
if you suddenly realized you needed to do those things, you had to refactor your
code to not use block-based callbacks.
• NSURLConnection: if we have an open connection with
NSURLConnection and the system interrupt our App, when our App goes to
background mode, everything we have received or sent were lost.
• NSURLSession: solve this problem and also give us out of process
downloads. It manage the connection process even when we don’t have
access. You will need to use
application:handleEventsForBackgroundURLSession:completionHandler in
your AppDelegate

378.Differences Between Swift And Objective-C


1. Optionals
Optionals are a concept which doesn’t exist in C or Objective-C. They allow
functions which may not always be able to return a meaningful value (e.g. in the
event of invalid input) to return either a value encapsulated in an optional or nil.
In C and Objective-C, we can already return nil from a function that would
normally return an object, but we don’t have this option for functions which are
expected to return a basic type such as int, float, or double.
2. Control Flow
Anyone who’s programmed in C or a C-like language is familiar with the use of
curly braces ({}) to delimit code blocks. In Swift, however, they’re not just a
good idea: they’re the law!
3. Type Inference
Swift introduces type safety to iOS development. Once a variable is declared with
a particular type, its type is static and cannot be changed. The compiler is also
smart enough to figure out (or infer) what type your variables should be based on
the values you assign them:
4. Tuples
Swift supports tuples, values which store groups of other values. Unlike arrays,
the values in a tuple don’t have to all be the same type. For example, you can
have a tuple of Strings and Ints:
5. String Manipulation
Swift offers huge improvements over Objective-C in terms of string
manipulation. For starters, you don’t have to worry about mutable vs. immutable
strings anymore: just declare your string with var if you want to change it in the
future, or with let if you need it to remain constant.
6. Guard And Defer
Now that’s a pyramid that would make even Indiana Jones blink! Fortunately, in
Swift, we have guard, a new conditional statement which can make this code
much more readable. Guard stops program flow if a condition is not met:
What defer does is not obvious at first. Defer will wait to execute a block of code
until the current scope (loop, method, etc) is exiting. And it will execute that code
whether the scope is exiting cleanly, from a guard, or while an error is being
thrown.
Here’s the most basic of examples. The defer block exists before the main body
of the code, but it’s not called until afterwards.
7. Functional Programming Patterns
Swift incorporates a number of functional programming features, such as map
and filter, which can be used on any collection which implements the
CollectionType protocol:
8. Enumerations
In Swift, enumerations are more powerful than they ever were in Objective-C:
they can now contain methods and be passed by value. Here’s a little snippet of
code which nicely illustrates how enums work in Swift:
9. Functions
Swift’s function syntax is flexible enough to define anything from a simple C-
style function to a complex Objective-C-style method with local and external
parameter names.
Every function in Swift has a type, which consists of the function’s parameter
types and return type. This means you can assign functions to variables or pass
them as parameters to other functions:
10. Do Statement
The do statement in Swift allows you to introduce a new scope:
Do statements can also contain one or more catch clauses:

378. nil / Nil / NULL / NSNull

Symbol Value Meaning

literal null
NULL (void *)0 value for C
pointers

literal null
value for
nil (id)0
Objective-C
objects

literal null
value for
Nil (Class)0
Objective-C
classes
singleton
[NSNull object used
NSNull
null] to represent
null

379.What is an API
API is the acronym for Application Programming Interface, which is a software
intermediary that allows two applications to talk to each other. Each time you use
an app like Facebook, send an instant message, or check the weather on your
phone, you’re using an API.
When you use an application on your mobile phone, the application connects to
the Internet and sends data to a server. The server then retrieves that data,
interprets it, performs the necessary actions and sends it back to your phone. The
application then interprets that data and presents you with the information you
wanted in a readable way. This is what an API is - all of this happens via API.
To explain this better, let us take a familiar example.
Imagine you’re sitting at a table in a restaurant with a menu of choices to order
from. The kitchen is the part of the “system” that will prepare your order. What is
missing is the critical link to communicate your order to the kitchen and deliver
your food back to your table. That’s where the waiter or API comes in. The waiter
is the messenger – or API – that takes your request or order and tells the kitchen –
the system – what to do. Then the waiter delivers the response back to you; in this
case, it is the food.

380- What is the difference Stack and Heap ?


Our code takes up some space in the iOS. The size of this is sometimes fixed
and sometimes it can change according to what the user will enter during the
program. Basically we have two different methods because of this difference:
Stack and Heap
Stack is used and automatically removes itself from memory after work is
finished. But in Heap the user could do it by writing manual code for deleting
from memory.
Stack;
Stack is easy to use.
It’s kept in RAM on the computer.
Created variables are automatically deleted when they exit the stack.
It is quite fast compared to Heap.
Constructed variables can be used without a pointer.
Heap;
Compared to Stack, it is quite slow.
It creates memory problems if not used correctly.
Variables are used with pointers.
It is created at runtime.
381.Coredata
The first step is to create a managed object model, which describes the way Core
Data represents data on disk.
By default, Core Data uses a SQLite database as the persistent store, so you can
think of the Data Model as the database schema.

• An entity is a class definition in Core Data. The classic example is an


Employee or a Company. In a relational database, an entity corresponds to a
table.
• An attribute is a piece of information attached to a particular entity. For
example, an Employee entity could have attributes for the employee’s name,
position and salary. In a database, an attribute corresponds to a particular
field in a table.
• A relationship is a link between multiple entities. In Core Data, relationships
between two entities are called to-one relationships, while those between
one and many entities are called to-many relationships. For example, a
Manager can have a to-many relationship with a set of employees, whereas
an individual Employee will usually have a to-one relationship with his
manager.

In Core Data, an attribute can be of one of several data types. Set the new
attribute’s name to, er, name and change its type to String:
NSManagedObject represents a single object stored in Core Data; you must use it
to create, edit, save and delete from your Core Data persistent store. As you’ll see
shortly, NSManagedObject is a shape-shifter. It can take the form of any entity in
your Data Model, appropriating whatever attributes and relationships you defined.
This is where Core Data kicks in! Here’s what the code does:
1 Before you can save or retrieve anything from your Core Data store, you
first need to get your hands on an NSManagedObjectContext. You can
consider a managed object context as an in-memory “scratchpad” for
working with managed objects.

Think of saving a new managed object to Core Data as a two-step process:
first, you insert a new managed object into a managed object context; then,
after you’re happy with your shiny new managed object, you “commit” the
changes in your managed object context to save it to disk.

Xcode has already generated a managed object context as part of the new
project’s template. Remember, this only happens if you check the Use Core
Data checkbox at the beginning. This default managed object context lives
as a property of the NSPersistentContainer in the application delegate. To
access it, you first get a reference to the app delegate.
2 You create a new managed object and insert it into the managed object
context. You can do this in one step with NSManagedObject’s static method:
entity(forEntityName:in:).

You may be wondering what an NSEntityDescription is all about. Recall
earlier, NSManagedObject was called a shape-shifter class because it can
represent any entity. An entity description is the piece linking the entity
definition from your Data Model with an instance of NSManagedObject at
runtime.
3 With an NSManagedObject in hand, you set the name attribute using key-
value coding. You must spell the KVC key (name in this case) exactly as it
appears in your Data Model, otherwise your app will crash at runtime.
4 You commit your changes to person and save to disk by calling save on the
managed object context. Note save can throw an error, which is why you
call it using the try keyword within a do-catch block. Finally, insert the new
managed object into the people array so it shows up when the table view
reloads.

1 Before you can do anything with Core Data, you need a managed object
context. Fetching is no different! Like before, you pull up the application
delegate and grab a reference to its persistent container to get your hands on
its NSManagedObjectContext.
2 As the name suggests, NSFetchRequest is the class responsible for fetching
from Core Data. Fetch requests are both powerful and flexible. You can use
fetch requests to fetch a set of objects meeting the provided criteria (i.e. give
me all employees living in Wisconsin and have been with the company at
least three years), individual values (i.e. give me the longest name in the
database) and more.

Fetch requests have several qualifiers used to refine the set of results
returned. For now, you should know NSEntityDescription is a required one
of these qualifiers.

Setting a fetch request’s entity property, or alternatively initializing it with
init(entityName:), fetches all objects of a particular entity. This is what you
do here to fetch all Person entities. Also note NSFetchRequest is a generic
type. This use of generics specifies a fetch request’s expected return type, in
this case NSManagedObject.
3 You hand the fetch request over to the managed object context to do the
heavy lifting. fetch(_:) returns an array of managed objects meeting the
criteria specified by the fetch request.

When we talk about persistent data, people probably think of database. If you are
familiar with Oracle or MySQL, you know that relational database stores data in
the form of table, row and column, and it usually facilitates access through what-
so-called SQL query. However, don’t mix up Core Data with database. Though
SQLite database is the default persistent store for Core Data on iPhone, Core Data
is not a relational database. It is actually a framework that lets developers store (or
retrieve) data in database in an object-oriented way. With Core Data, you can
easily map the objects in your apps to the table records in the database without
even knowing any SQL.
Managed Object Model – It describes the schema that you use in the app. If you
have a database background, think of this as the database schema. However, the
schema is represented by a collection of objects (also known as entities). In Xcode,
the Managed Object Model is defined in a file with the extension .xcdatamodeld.
You can use the visual editor to define the entities and their attributes, as well as,
relationships.
Persistent Store Coordinator – SQLite is the default persistent store in iOS.
However, Core Data allows developers to setup multiple stores containing
different entities. The Persistent Store Coordinator is the party responsible to
manage different persistent object stores and save the objects to the stores. Forget
about it you don’t understand what it is. You’ll not interact with Persistent Store
Coordinator directly when using Core Data.
Managed Object Context – Think of it as a “scratch pad” containing objects that
interacts with data in persistent store. Its job is to manage objects created and
returned using Core Data. Among the components in the Core Data Stack, the
Managed Object Context is the one you’ll work with for most of the time. In
general, whenever you need to fetch and save objects in persistent store, the
context is the first component you’ll talk to.
The below illustration can probably give you a better idea about the Core Data
Stack:
Core Data Stack

You might also like