iOS InterView Que Ans
iOS InterView Que Ans
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.
• 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.
{
[_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];
}
• If you override existing methods of the class, your application may behave
unpredictably.
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.
property uses a lock and retains and autoreleases the returned value—
the implementation will be similar to the following:
[_internal unlock];
return result;
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.
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?
“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.
ui view table view data source three method namely (1)No of sections.
(2)No of rows in sections.
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
Controller: controller is used for by getting the data from model and
controls the views.
Void is return type which does not giving any thing here. Click me is
method name.
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.
}
(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;
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:
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.
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
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 also does not allow stack based objects. Each object must be
a pointer to a block of memory.
· 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:
[friend gossipAbout:aNeighbor];
117-Class Introspection
· Determine whether an objective-C object is an instance of a class
[obj isMemberOfClass:someClass];
[obj isKindOfClass:someClass];
· The version of a class
[MyString version]
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.
//someMethod();
@end
· 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;
}
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:
· Create instances of NSThread and start them at a later time using the
“start” method.
Core 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
Can create millions of new objects in-memory very quickly (although saving
these objects will be slow)
When object A retains object B, and object B retains A. Then Retain cycle
happens. To overcome this use “close” method.
Foo.h
@interface Foo:NSObject @property(readonly, copy) NSString *bar;
-(void) publicSaucing;
@end
Foo.m
@interface Foo()
@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.
@end
@implementation AbstractClass
+ (id)alloc{
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.
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.
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;
1) Subclass in Objective C
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
Example:
Lets create a category class with a name something like
NSString +NSString_ReverseString
NSString+NSString_ReverseString.h
#import <Foundation/Foundation.h>
NSString+NSString_ReverseString.m
#import "NSString+NSString_ReverseString.h"
[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.
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
@end
since no name is given in the parentheses, class extensions are often referred to
as anonymous categories.
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);
}
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.
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.
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?
{
CGFloat area;
}
- (void)printArea;
- (void)calculateArea;
@end
@implementation Shape
- (void)printArea{
NSLog(@"The area is %f", area);
}
- (void)calculateArea{
@end
- (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
@end
@implementation Rectangle
- (id)initWithLength:(CGFloat)rLength andBreadth:(CGFloat)rBreadth{
length = rLength;
breadth = rBreadth;
return self;
}
- (void)calculateArea{ area
= length * breadth;
}
@end
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
@end
@implementation MyConcreteClass
@end
If you are concerned over using the same name for a class and a protocol look
at Cocoa where NSObject follows this pattern…
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.
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.
• 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.
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.
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.
is equivalent to:
[friend gossipAbout:aNeighbor];
198.Class Introspection
[obj isKindOfClass:someClass];
· The version of a class
[MyString version]
217.Strong vs Weak
The strong and weak are new ARC types replacing retain and
assign respectively.
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.
Using Testflight
localizedCaseInsensitiveCompare
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");
}
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.
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
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
244.List out what are the control transfer statements used in Swift?
Control transfer statements used in Swift includes
• Continue
• Break
• Fallthrough
• Return
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
262.Can you spot the bug in the following code and suggest how to fix it:
@interface MyCustomController : UIViewController
@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";
});
});
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);
}
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.
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.
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.
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.
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.
302.Explain subscripts ?
Classes, structures, and enumerations can define subscripts, which are shortcuts
for accessing the member elements of a collection, list, or sequence.
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.
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.
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.
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.
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.
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.
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.
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.
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:
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.
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:
256bytes.
sqlite3_open
sqlite3_prepare_v2
sqlite3_step
sqlite3_finalize
sqlite3_close
SQLITE_OK
SQLITE_ROW
NSobject.
358. Default constructor syntax is?
- (id) init.
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.
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.
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.
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.
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.
[b setTitle:@“adding" forState:UIControlStateNormal];
b.frame=CGRectMake(10,420, 100,30 );
[b addTarget:self action:@selector(show)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:b];
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.
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!
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.
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
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.
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.
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…
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
Generic Subscripts
Subscripts can now have generic arguments and return types 🚀
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.
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.
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