Interview
Interview
Interview
5- What is Enum ?
Read only, we can set the property initially but then it can’t be
changed.
Copy, means that we’re copying the value of the object when it’s
created. Also prevents its value from changing.
Pro Tip, Good functions accept input and return output. Bad
functions set global variables and rely on other functions to
work.
Creational: Singleton.
Structural: Decorator, Adapter, Facade.
Behavioral: Observer, and, Memento
Your view model will actually take in your model, and it can
format the information that’s going to be displayed on your
view.
46- 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;
48- KVC — KVO
KVC adds 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.
Method Swizzling is a well known practice in Objective-C and in other languages that
support dynamic method dispatching.
Through swizzling, the implementation of a method can be replaced with a different one at
runtime, by changing the mapping between a specific #selector(method) and the function that
contains its implementation.
To use method swizzling with your Swift classes there are two requirements that you must
comply with:
Escaping closure means, inside the function, you can still run the closure (or not); the extra
bit of the closure is stored some place that will outlive the function. There are several ways to
have a closure escape its containing function:
unowned ( non-strong reference ) does the same as weak with one exception: The variable
will not become nil and must not be an optional.
When you try to access the variable after its instance has been deallocated. That means, you
should only use unowned when you are sure, that this variable will never be accessed after
the corresponding instance has been deallocated.
However, if you don’t want the variable to be weak AND you are sure that it can’t be
accessed after the corresponding instance has been deallocated, you can use unowned.
4- What is ARC ?
ARC is a compile time feature that is Apple’s version of automated memory management. It
stands for Automatic Reference Counting. This means that it only frees up memory for
objects when there are zero strong references/ to them.
5- Explain #keyPath() ?
Using #keyPath(), a static type check will be performed by virtue of the key-path literal string
being used as a StaticString or StringLiteralConvertible. At this point, it’s then checked to
ensure that it
1. (Unlike PhoneGap) with React Native your application logic is written and runs in
JavaScript, whereas your application UI is fully native; therefore you have none of the
compromises typically associated with HTML5 UI.
2. Additionally (unlike Titanium), React introduces a novel, radical and highly
functional approach to constructing user interfaces. In brief, the application UI is
simply expressed as a function of the current application state.
8- What is NSFetchRequest ?
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, individual values and more.
9- Explain NSPersistentContainer ?
The persistent container creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate error conditions that
could cause the creation of the store to fail.
Set up an NSFetchedResultsController correctly, and your table will mimic its data source
without you have to write more than a few lines of code.
The View Debugger lets us visualize our layouts and see constraint definitions at
runtime. Although this has been around since Xcode 6, Xcode 8 introduces some
handy new warnings for constraint conflicts and other great convenience features.
The Thread Sanitizer is an all new runtime tool in Xcode 8 that alerts you to
threading issues — most notably, potential race conditions.
The Memory Graph Debugger is also brand new to Xcode 8. It provides
visualization of your app’s memory graph at a point in time and flags leaks in the
Issue navigator.
1. You are not allowed to write any production code unless it is to make a failing unit
test pass.
2. You are not allowed to write any more of a unit test than is sufficient to fail; and
compilation failures are failures.
3. You are not allowed to write any more production code than is sufficient to pass the
one failing unit test.
By adding the keyword final in front of the method name, we prevent the method from being
overridden. If we can replace the final class keyword with a single word static and get the
same behavior.
Yak shaving is a programing term that refers to a series of tasks that need to be performed
before a project can progress to its next milestone.
15- What is the difference open & public access level ?
open allows other modules to use the class and inherit the class; for members, it allows others
modules to use the member and override it.
public only allows other modules to use the public classes and the public members. Public
classes can no longer be subclassed, nor public members can be overridden.
16- What is the difference fileprivate, private and public private(set) access level ?
fileprivate is accessible within the current file, private is accessible within the current
declaration.
Internal access enables entities to be used within any source file from their defining module,
but not in any source file outside of the module.
Internal access is the default level of access. So even though we haven’t been writing any
access control specifiers in our code, our code has been at an internal level by default.
The main difference between BDD and TDD is the fact that BDD test cases can be read by
non-engineers, which can be very useful in teams.
iOS I prefer Quick BDD framework and its “matcher framework,” called Nimble.
AAA is a pattern for arranging and formatting code in Unit Tests. If we were to write
XCTests each of our tests would group these functional sections, separated by blank lines:
Writing tests first gives us a clear perspective on the API design, by getting into the
mindset of being a client of the API before it exists.
Good tests serve as great documentation of expected behavior.
It gives us confidence to constantly refactor our code because we know that if we
break anything our tests fail.
If tests are hard to write its usually a sign architecture could be improved. Following
RGR ( Red — Green — Refactor ) helps you make improvements early on.
21- What is five essential practical guidelines to improve your typographic quality of
mobile product designs ?
When we defined a variable as optional, then to get the value from this variable, we will
have to unwrap it. This just means putting an exclamation mark at the end of the variable.
Education in context technique helping users interact with an element or surface in a way
they have not done so previously. This technique often includes slight visual cues and subtle
animation.
Bitcode refers to to the type of code: “LLVM Bitcode” that is sent to iTunes Connect. This
allows Apple to use certain calculations to re-optimize apps further (e.g: possibly downsize
executable sizes). If Apple needs to alter your executable then they can do this without a new
build being uploaded.
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.
SVN relies on a centralised system for version management. It’s a central repository where
working copies are generated and a network connection is required for access.
Git relies on a distributed system for version management. You will have a local repository
on which you can work, with a network connection only required to synchronise.
TableViews display a list of items, in a single column, a vertical fashion, and limited to
vertical or horizontal scrolling only.
CollectionViews also display a list of items, however, they can have multiple columns and
rows.
Alamofire uses URL Loading System in the background, so it does integrate well with the
Apple-provided mechanisms for all the network development. This means, It provides
chainable request/response methods, JSON parameter and response serialization,
authentication, and many other features. It has thread mechanics and execute requests on a
background thread and call completion blocks on the main thread.
HTTP is the application protocol, or set of rules, web sites use to transfer data from the web
server to client. The client (your web browser or app) use to indicate the desired action:
GET: Used to retrieve data, such as a web page, but doesn’t alter any data on the
server.
HEAD: Identical to GET but only sends back the headers and none of the actual data.
POST: Used to send data to the server, commonly used when filling a form and
clicking submit.
PUT: Used to send data to the specific location provided.
DELETE: Deletes data from the specific location provided.
REST, or REpresentational State Transfer, is a set of rules for designing consistent, easy-to-
use and maintainable web APIs.
Code encapsulation
Code modularity
Code reuse
You can share your framework with your other apps, team members, or the iOS community.
When combined with Swift’s access control, frameworks help define strong, testable
interfaces between code modules.
The Swift Package Manager only supports using the master branch. Swift Package Manager
now supports packages with Swift, C, C++ and Objective-C.
Delegates and NSNotifications can be used to accomplish nearly the same functionality.
However, delegates are one-to-one while NSNotifications are one-to-many.
35- Why do we use a delegate pattern to be notified of the text field’s events?
Because at most only a single object needs to know about the event.
- loadView
Creates the view that the controller manages. It’s only called when the view controller is
created and only when done programatically. It is responsible for making the view property
exist in the first place.
- viewDidLoad
Called after the controller’s view is loaded into memory. It’s only called when the view
is created.
- viewWillAppear
It’s called whenever the view is presented on the screen. In this step the view has bounds
defined but the orientation is not applied.
- viewWillLayoutSubviews
Called to notify the view controller that its view is about to layout its subviews. This method
is called every time the frame changes
- viewDidLayoutSubviews
Called to notify the view controller that its view has just laid out its subviews. Make
additional changes here after the view lays out its subviews.
- viewDidAppear
Notifies the view controller that its view was added to a view hierarchy.
- viewWillDisappear
Before the transition to the next view controller happens and the origin view controller gets
removed from screen, this method gets called.
- viewDidDisappear
After a view controller gets removed from the screen, this method gets called. You usually
override this method to stop tasks that are should not run while a view controller is not
on screen.
- viewWillTransition(to:with:)
When the interface orientation changes, UIKit calls this method on the window’s root view
controller before the size changes are about to be made. The root view controller then
notifies its child view controllers, propagating the message throughout the view controller
hierarchy.
Clang is the front end of LLVM tool chain ( “clang” C Language Family Frontend for LLVM
). Every Compiler has three parts .
1. Front end ( lexical analysis, parsing )
2. Optimizer ( Optimizing abstract syntax tree )
3. Back end ( machine code generation )
Front end ( Clang ) takes the source code and generates abstract syntax tree ( LLVM IR ).
A class is meant to define an object and how it works. In this way, a class is like a blueprint
of an object.
The @interface in Objective-C has nothing to do with Java interfaces. It simply declares a
public interface of a class, its public API.
45- What are the most important application delegate methods a developer should
handle ?
The operating system calls specific methods within the application delegate to facilitate
transitioning to and from various states. The seven most important application delegate
methods a developer should handle are:
application:willFinishLaunchingWithOptions
Method called when the launch process is initiated. This is the first opportunity to execute
any code within the app.
application:didFinishLaunchingWithOptions
Method called when the launch process is nearly complete. Since this method is called is
before any of the app’s windows are displayed, it is the last opportunity to prepare the
interface and make any final adjustments.
applicationDidBecomeActive
Once the application has become active, the application delegate will receive a callback
notification message via the method applicationDidBecomeActive.
This method is also called each time the app returns to an active state from a previous switch
to inactive from a resulting phone call or SMS.
applicationWillResignActive
There are several conditions that will spawn the applicationWillResignActive method. Each
time a temporary event, such as a phone call, happens this method gets called. It is also
important to note that “quitting” an iOS app does not terminate the processes, but rather
moves the app to the background.
applicationDidEnterBackground
This method is called when an iOS app is running, but no longer in the foreground. In other
words, the user interface is not currently being displayed. According to Apple’s
UIApplicationDelegate Protocol Reference, the app has approximately five seconds to
perform tasks and return. If the method does not return within five seconds, the application is
terminated.
applicationWillEnterForeground
This method is called as an app is preparing to move from the background to the foreground.
The app, however, is not moved into an active state without the applicationDidBecomeActive
method being called. This method gives a developer the opportunity to re-establish the
settings of the previous running state before the app becomes active.
applicationWillTerminate
This method notifies your application delegate when a termination event has been triggered.
Hitting the home button no longer quits the application. Force quitting the iOS app, or
shutting down the device triggers the applicationWillTerminate method. This is the
opportunity to save the application configuration, settings, and user preferences.
A property is a more abstract concept. An instance variable is literally just a storage slot, like
a slot in a struct. Normally other objects are never supposed to access them directly. Usually
a property will return or set an instance variable, but it could use data from several or none at
all.
Swift Package Manager is not supporting UIKit. We can create File Template or Framework
for other projects.
SDK is a set of software development tools. This set is used for creation of applications.
Framework is basically a platform which is used for developing software applications. It
provides the necessary foundation on which the programs can be developed for a specific
platform. SDK and Framework complement each other, and SDKs are available for
frameworks.
3- Explain subscripts ?
Classes, structures, and enumerations can define subscripts, which are shortcuts for accessing
the member elements of a collection, list, or sequence.
4- What is DispatchGroup ?
DispatchGroup allows for aggregate synchronization of work. We can use them to submit
multiple different work items and track when they all complete, even though they might run
on different queues. This behavior can be helpful when progress can’t be made until all of the
specified tasks are complete. — Apple’s Documentation
Red, Green and Refactor are stages of the TDD (Test Driven Development).
1. Red: Write a small amount of test code usually no more than seven lines of code and
watch it fail.
2. Green: Write a small amount of production code. Again, usually no more than seven
lines of code and make your test pass.
3. Refactor: Tests are passing, you can make changes without worrying. Clean up your
code. There are great workshop notes here.
We use a storyboard or xib in our iOS app, then we created IBOutlets. IBOutlet is a property
related to a view. These are injected into the view controller when it is instantiated, which is
essentially a form of Dependency Injection.
There are forms of dependency injection: constructor injection, property injection and
method injection.
There are two type of notifications: Remote and Local. Remote notification requires
connection to a server. Local notifications don’t require server connection. Local
notifications happen on device.
Rules 3. If an object is creating instances of other objects that are shared dependencies within
other objects then it is a good candidate for a dependency injection.
map(_:): Returns an array of results after transforming each element in the sequence
using the provided closure.
filter(_:): Returns an array of elements that satisfy the provided closure predicate.
reduce(_:_:): Returns a single value by combining each element in the sequence
using the provided closure.
sorted(by:): Returns an array of the elements in the sequence sorted based on the
provided closure predicate.
To see all methods available from Sequence, take a look at the Sequence docs.
10- What allows you to combine your commits ?
git squash
Any can represent an instance of any type at all, including function types and
optional types.
AnyObject can represent an instance of any class type.
Both of them helps us access Web services. SOAP relies exclusively on XML to provide
messaging services. SOAP is definitely the heavyweight choice for Web service access.
Originally developed by Microsoft.
Charts has support iOS,tvOS,OSX The Apple side of the cross platform MPAndroidChart.
A curated list of awesome iOS chart libraries, including Objective-C and Swift
Map, we pass in a function that returns a value for each element in an array. The return value
of this function represents what an element becomes in our new array.
Filter, we pass in a function that returns either true or false for each element. If the function
that we pass returns true for a given element, then the element is included in the final array.
Core data is an object graph manager which also has the ability to persist object graphs to the
persistent store on a disk. An object graph is like a map of all the different model objects in a
typical model view controller iOS application. CoreData has also integration with Core
Spotlight.
But Core Data is not thread safe, meaning that, if you load a managed object on one thread,
you can’t pass it to another thread and use it safely. This becomes an issue when we want to
start introducing threading for performance, so we have two choices.
The first is to keep everything on the main thread, which just means it’s single threaded. Or
the second, means making changes on background threads and passing managed object IDs
and then loading those objects again on the main thread, but that would mean that you’re on
the main thread, which puts us right back where we started. Both of these kind of ruin the
point of using threading within Core Data and they can add a lot of complexity to the data
layer.
There’s also another option for that and it’s to convert the managed object to a plain old Swift
object, or a POSO.
If you want to create Generic Protocol we can use associatedtype. For more details check this
out.
17- Which git command saves your code without making a commit ?
git stash
If high priority thread waits for low priority thread, this is called Priority Inversion. if low
priority thread temporarily inherit the priority of the highest priority thread, this is called
Priority Inheritance.
Hashable allows us to use our objects as keys in a dictionary. So we can make our custom
types.
We use optional chaining when we do not really care if the operation fails; otherwise, we use
if let or guard. Optional chaining lets us run code only if our optional has a value.
Using the question mark operator like this is called optional chaining. Apple’s documentation
explains it like this:
Optional chaining is a process for querying and calling properties, methods, and subscripts
on an optional that might currently be nil. If the optional contains a value, the property,
method, or subscript call succeeds; if the optional is nil, the property, method, or subscript
call returns nil. Multiple queries can be chained together, and the entire chain fails gracefully
if any link in the chain is nil.
I follow style guide and coding conventions for Swift projects of Github and SwiftLint.
There is no difference. Optional.None (.None for short) is the correct way of initializing an
optional variable lacking a value, whereas nil is just syntactic sugar for .None. Check this
out.
GraphQL is trying to solve creating a query interface for the clients at the application level.
Apollo iOS is a strongly-typed, caching GraphQL client for iOS, written in Swift.
implementation reuse
provide points for customization
interface reuse
supporting modular design via dynamic dispatch on reused interfaces
Continuous Integration allows us to get early feedback when something is going wrong
during application development. There are a lot of continuous integration tools available.
Xcode Server
Jenkins
TeamCity
Cloud solutions
TravisCI
Bitrise
Buddybuild
28- What is the difference Delegates and Callbacks ?
The difference between delegates and callbacks is that with delegates, the NetworkService is
telling the delegate “There is something changed.” With callbacks, the delegate is observing
the NetworkService.
Linked List basically consist of the structures we named the Node. These nodes basically
have two things. The first one is the one we want to keep. (we do not have to hold single data,
we can keep as much information as we want), and the other is the address information of the
other node.
Disadvantages of Linked Lists, at the beginning, there is extra space usage. Because the
Linked List have an address information in addition to the existing information. This means
more space usage.
Depends. I have experienced PARSE and I am awarded FBStart. I decided to learn pure back
end. You have two choices. Either you can learn node.js + express.js and mongodb. OR, you
can learn Vapor or Kitura.
If you want to learn Firebase, please just follow one month of Firebase Google Group.
AutoLayout provides a flexible and powerful layout system that describes how views and the
UI controls calculates the size and position in the hierarchy.
First, when you start to log. This starts to accumulate. It may not seem like a lot, but every
minute adds up. By the end of a project, those stray minutes will equal to hours.
Second, Each time we add one to the code base, we take a risk of injecting new bugs into our
code.
Cons:
Core ML only supports a limited number of model types. If you trained a model that
does something Core ML does not support, then you cannot use Core ML.
The conversion tools currently support only a few training packages. A notable
omission is TensorFlow, arguably the most popular machine learning tool out there.
You can write your own converters, but this isn’t a job for a novice. (The reason
TensorFlow is not supported is that it is a low-level package for making general
computational graphs, while Core ML works at a much higher level of abstraction.)
No flexibility, little control. The Core ML API is very basic, it only lets you load a
model and run it. There is no way to add custom code to your models.
iOS 11 and later only.
Pair programming is a tool to share information with junior developers. Junior and senior
developer sitting side-by-side this is the best way for the junior to learn from senior
developers.
Blocks are a way of defining a single task or unit of behavior without having to write an
entire Objective-C class. they are anonymous functions.
Keychain is an API for persisting data securly in iOS App. There is a good library -
Locksmith
39- Explain the difference between atomic and nonatomic synthesized properties
atomic : It is the default behaviour. If an object is declared as atomic then it becomes thread-
safe. Thread-safe means, at a time only one thread of a particular instance of that class can
have the control over that object.
nonatomic: It is not thread-safe. We can use the nonatomic property attribute to specify that
synthesized accessors simply set or return a value directly, with no guarantees about what
happens if that same value is accessed simultaneously from different threads. For this reason,
it’s faster to access a nonatomic property than an atomic one.
Apple wants to support one system version back, meaning that we should support iOS9 or
iOS8. Availability Attributes lets us to support previous version iOS.
There are two steps to get device token. First, we must show the user’s permission screen,
after we can register for remote notifications. If these steps go well, the system will provide
device token. If we uninstall or reinstall the app, the device token would change.
Encapsulation is an object-oriented design principles and hides the internal states and
functionality of objects. That means objects keep their state information private.
An algorithm is an impression method used to determine the working time for an input N
size. The big-o notation grade is expressed by the highest value. And the big-o notation is
finding the answer with the question of O(n). Here is a cheat sheet and swift algorithm
club. For example;
For Loops big-o notation is O(N). Because For Loops work n times.
Variables (var number:Int = 4) big-o notation is O(1).
If we want to integrate open source project, add a framework from a third party project, or
even reuse code across our own projects, dependency management helps us to manage these
relationships. Check this out
UML Class Diagram is a set of rules and notations for the specification of a software system,
managed and created by the Object Management Group.
46- Explain throw
We are telling the compiler that it can throw errors by using the throws keyword. Before we
can throw an error, we need to make a list of all the possible errors you want to throw.
We can adopt protocols using extensions as well as on the original type declaration. This
allows you to add protocols to types you don’t necessarily own.
Location, Calendar, and Time Interval. A Location notification fires when the GPS on your
phone is at a location or geographic region. Calendar trigger is based on calendar data broken
into date components. Time Interval is a count of seconds until the timer goes off.
We can be sent with video or image with push notification. But maximum payload is 4kb. If
we want to sent high quality attachment, we should use Notification Service Extension.
1- What is Functional programming ?
5- What’s accessibilityHint?
accessibilityHint describes the results of interacting with a user
interface element. A hint should be supplied only if the result of
an interaction is not obvious from the element’s label.
Xcode server will automatically check out our project, build the
app, run tests, and archive the app for distribution.
p1
|\
|\
| \H
| \
| \
|_ _ _\
p2
3- Explain IGListKit
4- What is URLSession?
8- Explain IteratorProtocol
The IteratorProtocol protocol is tightly linked with the Sequence protocol.
Sequences provide access to their elements by creating an
iterator, which keeps track of its iteration process and returns
one element at a time as it advances through the sequence.
There are very good examples on the differences
ofIteratorProtocol from for loop and while loop.
9- Explain differences between WKWebView and
UIWebView
WKWebView has own cookie storage and its not share by the
whole app and all other web views like in the case of
(UIWebView).
Pros
Cons
XLIFF does not give them that visual and functional context.
XLIFF does not provide the resource data like assets in your
project.
XLIFF does not provide with the custom metadata about the
generated XLIFF.
Using this value, the scrollView can compute its new bounds
and redraw any of its subviews.
Queues are used to store a set of data, but are different in that
the first item to go into this collection, will be the first item to be
removed. Also well known as FIFO which means, ‘first in first
out’.
Swift uses type inference to work out the appropriate type. Type
inference enables a compiler to deduce the type of a particular
expression automatically when it compiles your code, simply
by examining the values you provide.
Our code takes up some space in the iOS. The size of this is
sometimes fixed and sometimes it can change according to what
the user will enter during the program. Basically we have two
different methods because of this difference: Stack and Heap
Stack;
Heap;
We’re going to create the task. We’re going to receive the data
back from the server. And we’re going to handle it based on if
there’s any errors and what the data is.
For example single view, a view object tracks its size and
location using a frame and bounds. A frame is a rectangle,
which specifies the size and location of the view within its
SuperView coordinate system.
A bounds rectangle, on the other hand, specifies the size of the
view within its own local coordinate system. Please remember
part 1.
If you use AnyObject, the compiler has no idea if the object can
be treated as a String or as an Integer. It will allow you to do
whatever you want with it.
3. How can we prevent iOS 8 app's streaming video media from being captured
by QuickTime Player on Yosemite during screen recording?
HTTP Live Streams that have their media encrypted will not be recorded by
QuickTime Player on Yosemite while screen recording. These will black out in the
recording.
• HTTP Live Streaming: – Send live and on‐ demand audio and video to iPhone,
iPad, Mac, Apple TV, and PC with HTTP Live Streaming (HLS) technology from
Apple. Using the same protocol that powers the web, HLS lets you deploy content
using ordinary web servers and content delivery networks. HLS is designed for
reliability and dynamically adapts to network conditions by optimizing playback for
the available speed of wired and wireless connections.
4. Name the framework that is used to construct application’s user interface
for iOS
In addition to the core app behaviors, UIKit provides support for the following
features:
✓ A view controller model to encapsulate the contents of your user interface
✓ Support for handling touch and motion-based events
✓ Support for a document model that includes iCloud integration
✓ Graphics and windowing support, including support for external displays
✓ Support for managing the app’s foreground and background execution
✓ Printing support
✓ Support for customizing the appearance of standard UIKit controls
✓ Support for text and web content
✓ Cut, copy, and paste support
✓ Support for animating user-interface content
✓ Integration with other apps on the system through URL schemes and framework
interfaces
✓ Accessibility support for disabled users
✓ Support for the Apple Push Notification service
✓ Local notification scheduling and delivery
✓ PDF creation
✓ Support for using custom input views that behave like the system keyboard
✓ Support for creating custom text views that interact with the system keyboard
✓ Support for sharing content through email, Twitter, Facebook, and other services
Check this tutorial, to learn more about iOS user interface.
5. How can you respond to state transitions on your app?
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
the 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.
6. What are the features added in iOS 9?
if (_variable != object)
{
[_variable release];
_variable = nil;
_variable = object;
}
Retain creates a reference from one object to another and increases the retain count
of the source object.
if (_variable != object)
{
[_variable release];
_variable = nil;
_variable = [object retain];
}
Foo.h
@interface Foo:NSObject
@property(readonly, copy) NSString *bar;
-(void) publicSaucing;
@end
Foo.m
@interface Foo()
@property(readwrite, copy) NSString *bar;
- (void) superSecretInternalSaucing;
@end
@implementation Foo
@synthesize bar;
.... must implement the two methods or compiler will warn ....
@end
18. What is NSURLConnection class? Define its types and use case.
There are two ways of using NSURLConnection class. One is asynchronous and the
other is synchronous.
An asynchronous connection will create a new thread and performs its download
process on the new thread. A synchronous connection will block the calling thread
while downloading content and doing its communication.
Many developers think that a synchronous connection blocks the main thread, which
is not true. A synchronous connection will always block the thread from which it is
fired. If you fire a synchronous connection from the main thread, the main thread will
be blocked. But, if you fire a synchronous connection from a thread other than the
main thread, it will be like an asynchronous connection and won’t block your main
thread.
In fact, the only difference between a synchronous and an asynchronous
connection is that at runtime, a thread will be created for the asynchronous
connection while it won’t do the same for a synchronous connection.
In order to create an asynchronous connection, we need to do the following:
1. Have our URL in an instance of NSString
2. Convert our string to an instance of NSURL
3. Place our URL in an URL Request of type NSURLRequest, or in the case of
mutable URLs, in an instance of NSMutableURLRequest.
4. Create an instance of NSURLConnection and pass the URL request to it.
Learn more about iOS, in this iOS online training course.
19. What is the relation between iVar and @property?
iVar is an instance variable. It cannot be accessed unless we create accessors,
which are generated by @property. iVar and its counterpart @property can be of
different names.
A
Four data types that you’ll definitely want your developer to be aware of
are as follows:
Q
How proficient are you in Objective-C and Swift? Can you briefly
describe their differences?
A
When Swift was first launched in 2014, it was aptly described as “Objective-
C without the C.” By dropping the legacy conventions that come with a
language built on C, Swift is faster, safer, easier to read, easier to maintain,
and designed specifically for the modern world of consumer-facing apps.
One of the most immediately visible differences is the fact that Objective-C
lacks formal support for namespaces, which forces Objective-C code to use
two- or three-letter prefixes to differentiate itself. Instead of simple names
like “String,” “Dictionary,” and “Array,” Objective-C must use oddities like
“NSString,” “NSDictionary,” and “NSArray.”
Another major advantage is that Swift avoids exposing pointers and other
“unsafe” accessors when referring to object instances. That said, Objective-
C has been around since 1983, and there is a mountain of Objective-C code
and resources available to the iOS developer. The best iOS developers tend
to be pretty well versed in both, with an understanding that Swift is the
future of iOS development.
Q
What are UI elements and some common ways you can add them
to your app?
A
Buttons, text fields, images, labels, and any other elements that are visible
within the application are called UI elements. These elements may be
interactive and comprise the user interface (hence the term “UI”) of an
application. In iOS development, UI elements can be quickly added through
Xcode’s interface builder, or coded from scratch and laid out using
NSLayoutConstraints and Auto Layout. Alternatively, each element can also
be positioned at exact coordinates using the UIView
“(id)initWithFrame:(CGRect)frame” method.
A
(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NS
String *)reuseIdentifier
The reuseIdentifier tells UITableView which cells may be reused within the
table, effectively grouping together rows in a UITableView that differ only
in content but have similar layouts. This improves scroll performance by
alleviating the need to create new views while scrolling. Instead the cell is
reused whenever dequeueReusableCellWithIdentifier: is called.
Q
A
The common execution states are as follows:
A
Managed object context exists for three reasons: life-cycle management,
notifications, and concurrency. It allows the developer to fetch an object
from a persistent store and make the necessary modifications before
deciding whether to discard or commit these changes back to the persistent
store. The managed object context tracks these changes and allows the
developer to undo and redo changes.
Q
A
var a1 = [1, 2, 3, 4, 5]
var a2 = a1
a2.append(6)
var x = a1.count
In Swift, arrays are implemented as structs, making them value types rather
than reference types (i.e., classes). When a value type is assigned to a
variable as an argument to a function or method, a copy is created and
assigned or passed. As a result, the value of “x” or the count of array “a1”
remains equal to 5 while the count of array “a2” is equal to 6, appending
the integer “6” onto a copy of the array “a1.” The arrays appear in the box
below.
a1 = [1, 2, 3, 4, 5]
a2 = [1, 2, 3, 4, 5, 6]
Q
Find the bug in the Objective-C code below. Explain your
answer.
A
@interface HelloWorldController : UIViewController
@end
@implementation HelloWorldController
- (void)viewDidLoad {
CGRect frame = CGRectMake(150, 150, 150, 50);
self.alert = [[UILabel alloc] initWithFrame:frame];
self.alert.text = @"Hello...";
[self.view addSubview:self.alert];
dispatch_async(
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT
, 0),
^{
sleep(10);
self.alert.text = @"World";
}
);
}
@end
All UI updates must be performed in the main thread. The global dispatch
queue does not guarantee that the alert text will be displayed on the UI. As
a best practice, it is necessary to specify any updates to the UI occur on the
main thread, as in the fixed code below:
dispatch_async(
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
,
^{
sleep(10);
dispatch_async(dispatch_get_main_queue(), ^{
self.alert.text = @"World";
});
});
Q
A
This question tests the developer’s understanding of enumeration in Swift.
Enumeration provides a type-safe method of working with a group of related
values. Raw values are compile time-set values directly assigned to every
case within an enumeration, as in the example detailed below:
case A = 1
case B
case C
In the above example code, case “A” was explicitly assigned a raw value
integer of 1, while cases “B” and “C” were implicitly assigned raw value
integers of 2 and 3, respectively. Associated values allow you to store values
of other types alongside case values, as demonstrated below:
case A(Int)
case B
case C(String)
You’ve just been alerted that your new app is prone to crashing.
What do you do?
This classic interview question is designed to see how well your prospective
programmer can solve problems. What you’re looking for is a general
methodology for isolating a bug, and their ability to troubleshoot issues like
sudden crashes or freezing. In general, when something goes wrong within
an app, a standard approach might look something like this:
o Once you have an idea as to the nature of the issue, acquire tooling
or create a unit test and begin debugging.
A great answer would include all of the above, with specific examples of
debugging tools like Buglife or ViewMonitor, and a firm grasp of software
debugging theory—knowledge on what to do with compile time errors, run-
time errors, and logical errors. The one answer you don’t want to hear is
the haphazard approach—visually scanning through hundreds of lines of code
until the error is found. When it comes to debugging software, a methodical
approach is must.