Wednesday 1 August 2018

Core Data - List the values, Add the Core Data

ListViewController.swift
import UIKit
import CoreData

class ListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
   
    var arr_Emp:[NSManagedObject] = retriveItem_CoreData(e_name: "", e_id: 0)
    @IBOutlet var tbl_view: UITableView?

    override func viewDidLoad() {
        super.viewDidLoad()

        tbl_view?.reloadData()
        // Do any additional setup after loading the view.
    }
   
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arr_Emp.count
    }
   
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:UITableViewCell = tbl_view?.dequeueReusableCell(withIdentifier: "cellReuseIdentifier") as UITableViewCell!
        let employee = arr_Emp[indexPath.row]
        cell.textLabel?.text = employee.value(forKey: "e_name") as? String
        cell.textLabel?.textAlignment = .center
        return cell
    }
   
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let add_vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "AddViewController") as? AddViewController
        add_vc?.page_id = 1234
        let employee = arr_Emp[indexPath.row]
        add_vc?.emp_Details = employee
        self.navigationController?.pushViewController(add_vc!, animated: true)
    }
}

AddViewController.swift
import UIKit
import CoreData

class AddViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBOutlet var txtfld_ename: UITextField!
    @IBOutlet var txtfld_eid: UITextField!
    @IBOutlet var txtfld_edest: UITextField!
    @IBOutlet var txtfld_eaddr: UITextField!
    @IBOutlet var btn_Map:UIButton!
    @IBOutlet var img_photo: UIImageView!
    @IBOutlet var lbl_NoPhoto: UILabel!
    
    @IBOutlet var btn_Save:UIButton!
    @IBOutlet var btn_Cancel:UIButton!
      
    var page_id:Int = 0
    var emp_Details:NSManagedObject? = NSManagedObject()
    var imagePicker = UIImagePickerController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "Add Data"
        imagePicker.delegate = self
        
        btn_Map.alpha = 0.0
        
        if page_id == 1234 {
            self.title = "View Data"
            
            txtfld_ename.isUserInteractionEnabled = false
            txtfld_eid.isUserInteractionEnabled = false
            txtfld_edest.isUserInteractionEnabled = false
            txtfld_eaddr.isUserInteractionEnabled = false
            
            txtfld_ename?.text = emp_Details?.value(forKey: "e_name") as? String
            txtfld_eid?.text = "\(emp_Details?.value(forKey: "e_id") as? Int)"
            txtfld_edest?.text = emp_Details?.value(forKey: "e_destination") as? String
            txtfld_eaddr?.text = emp_Details?.value(forKey: "e_address") as? String
            let str_photopath = emp_Details?.value(forKey: "e_photo_path") as? String
            if str_photopath != nil {
                img_photo.image =  GetImage(str_name: str_photopath!)
            }
            
            btn_Map.alpha = 1.0
            lbl_NoPhoto.alpha = 0.0
            
            btn_Save.alpha = 0.0
            btn_Cancel.alpha = 0.0
        }
        
        // Do any additional setup after loading the view.
    }

    @IBAction func browse_Action(_ sender: Any) {
        if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) {
            imagePicker.sourceType = .savedPhotosAlbum;
            imagePicker.allowsEditing = false
            self.present(imagePicker, animated: true, completion: nil)
        }
    }

    @IBAction func view_Action(_ sender: Any) {
        
    }
    
    @IBAction func openMap_Action(_ sender: Any) {
        let str_addr = txtfld_eaddr.text
        guard let url = URL(string: "https://www.google.com/maps/\(str_addr)") else {
            return
        }
        
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
        else {
            UIApplication.shared.openURL(url)
        }
    }
    
    
    @IBAction func save_Action(_ sender: Any) {
        let str_name = txtfld_ename.text
        let str_id = txtfld_eid.text
        let str_dest = txtfld_edest.text
        let str_addr = txtfld_eaddr.text
        
        let e_id_val:Int = Int(str_id!)!
        
        if img_photo.image != nil && (str_name?.characters.count)! > 0 && (str_id?.characters.count)! > 0 && (str_dest?.characters.count)! > 0 && (str_addr?.characters.count)! > 0 {
            let str_photoname = custom_name_generate()
            SaveImage(str_name: str_photoname, img_Save: img_photo.image!)
            let stats:Bool = saveItem_CoreData(e_name: str_name!, e_id: e_id_val, e_destination: str_dest!, e_address: str_addr!, e_photo_path: str_photoname)
            if stats == true {
                let actionSheetController: UIAlertController = UIAlertController(title: "Message!!!", message: "Your Item is Added to core data.", preferredStyle: .actionSheet)
                let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default) { action -> Void in
                    self.navigationController?.popViewController(animated: true)
                }
                actionSheetController.addAction(okAction)
                self.present(actionSheetController, animated: true, completion: nil)
            }
        }
        else {
            let actionSheetController: UIAlertController = UIAlertController(title: "Message!!!", message: "Please fill all details", preferredStyle: .actionSheet)
            let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default) { action -> Void in
            }
            actionSheetController.addAction(okAction)
            self.present(actionSheetController, animated: true, completion: nil)
        }
    }
    
    
    @IBAction func cancel_Action(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    
    //MARK: Text Field Delegate
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
    //MARK: Image Picker Delegate
    public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
            //save image
            //display image
            img_photo.image = image
            lbl_NoPhoto.alpha = 0.0
        }
        self.dismiss(animated: true, completion: nil)
    }
    
    public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        self.dismiss(animated: true, completion: nil)
    }
}

CommonClass.Swift
import Foundation
import UIKit
import CoreData

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let checkValidation = FileManager.default
let appDelegate = UIApplication.shared.delegate as? AppDelegate
let managedContext = appDelegate?.persistentContainer.viewContext

func saveItem_CoreData(e_name: String, e_id: Int, e_destination: String, e_address: String, e_photo_path: String) -> Bool {
    var stats = true
    let entity = NSEntityDescription.entity(forEntityName: "Employee", in: managedContext!)!
    let employee = NSManagedObject(entity: entity, insertInto: managedContext!)
    employee.setValue(e_name, forKeyPath: "e_name")
    employee.setValue(e_id, forKeyPath: "e_id")
    employee.setValue(e_destination, forKeyPath: "e_destination")
    employee.setValue(e_address, forKeyPath: "e_address")
    employee.setValue(e_photo_path, forKeyPath: "e_photo_path")
    do {
        try managedContext!.save()
    }
    catch let error as NSError {
        print("Could not save. \(error), \(error.userInfo)")
        stats = false
    }
    return stats
}

func retriveItem_CoreData(e_name: String, e_id: Int) -> [NSManagedObject] {
    var arr_Emp = [NSManagedObject]()
    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Employee")
    //fetchRequest.predicate = NSPredicate(format: "e_name == %@", e_name)
    do {
        arr_Emp = try managedContext!.fetch(fetchRequest)
        print(arr_Emp.count)
    }
    catch let error as NSError {
        print("Could not fetch. \(error), \(error.userInfo)")
    }
    return arr_Emp
}

func custom_name_generate() -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = "ddMMyyyy_HHmmss"
    let date_val = formatter.string(from: Date())
    let custom_name = "image_\(date_val).png"
    return custom_name
}

func SaveImage(str_name:String, img_Save:UIImage) {
    let getImagePath = paths.appending(str_name)
    if (checkValidation.fileExists(atPath: getImagePath))
    {
        print("Already Image saved samename")
    }
    else
    {
        let imageData =  UIImageJPEGRepresentation(img_Save, 1.0)
        try! imageData?.write(to: URL.init(fileURLWithPath: getImagePath), options: .atomicWrite)
    }
}

func GetImage(str_name:String) -> UIImage {
    var imgRetrive: UIImage = UIImage()
    let getImagePath = paths.appending(str_name)
    if (checkValidation.fileExists(atPath: getImagePath))
    {
        imgRetrive = UIImage(contentsOfFile: getImagePath)!
        //try! checkValidation.removeItem(atPath: getImagePath)
    }
    return imgRetrive
}




Wednesday 21 February 2018

iOS Interview Questions and Answers

What is latest iOS version?
IOS 11.0.3


What is latest Xcode version?
Xcode 9


What are the features in Xcode 9?
          - New Editor with Options
          - Refactor and Transform
          - New Simulators(Build System)
          - Swift 4.0 Supports
          - Cut the Cord [Through WiFi installation & Wireless Debugging]
          - Faster Search Results [Results are Instantly]

What are the features in iOS11?
          - New Files App
          - New Doc Menu At Bottom
          - Multi-Tasking(SlideOver/SplitView)
          - Drag and Drop option (One Application to Another)
          - Apple Pencil Support to Draw
          - Live Photos
          - Camera with More Options
          - AppStore New UI
          - Siri Updated
          - Control Centre UI Changed and Create you own
          - DND – Driving Mode


Which Programming Languages are used for iOS Development?
The languages used for iOS development are as follows:
  1. Objective-C
  2. Swift

Who invented Objective c?
Broad Cox and Tom Love


What are the Application lifecycle in iOS?
  • ApplicationDidFinishLaunchingWithOption
  • ApplicationWillResignActive
  • ApplicationDidBecomeActive
  • ApplicationWillTerminate

What is use of UIApplication delegate and Class?
UIApplicationDelegate is a Singleton class and loaded before UIView , this is accessible in whole application with same state of object because when you call
YourApplication *delegate = [[UIApplication sharedApplication] delegate];
The UIApplication class implements the required behavior of an application.
UIApplication Main creates an application execution in the system.


What compilers apple using?
The Apple compilers are based on the compilers of the GNU Compiler Collection.


App Launch Sequence – Picture?


Explain the difference between Cocoa and Cocoa Touch?
Cocoa is an Application Framework that enables development of Applications in Mac OS X Environment. It is basically a combination of two Frameworks i.e., Appkit Framework and Foundation Framework. Cocoa Touch is an Application Framework for iPod Touch. iPhone and iPad. It includes the Foundation Framework and UIKit Framework.


Enlist Frameworks for Cocoa Touch?
  1. Foundation
  2. UIKit

Does iOS supports Multiple Inheritance?
Not Supported.


What are the Layers in iPhone SDK?


What is a Framework?
It is basically a conceptual structure or a scheme with an intention to support the expansion of the structure into something useful. A Framework is a layered structure indicating what kind of programs can or should be built and how they would interact. Framework includes actual program that mentions programming interfaces and programming tools for working with the frameworks.


Does iOS supports Multi-Tasking functionality?
Multi-Tasking functionality is supported from iOS versions 4 and the later ones. Multi-Tasking is a feature that enables applications to remain in the background until it is re-launched or terminated.


What are the App States? Explain them?
  1. Not Running State: The app has not been launched or was running but was terminated by the system.
  2. Inactive State: The app is running in the foreground but is currently not receiving events. 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.
  3. Active State: The app is running in the foreground and is receiving events. This is the normal mode for foreground apps.
  4. 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.
  5. 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.

What is Xcode?
Xcode is a combination of Software Development Tools developed by Apple for developing applications. It is an Integrated Development Environment (IDE). It is primarily used for development of iOS and OS X applications.


Explain what is Xcode command line tools package?
Command line tools package is a self-contained package available separately from Xcode. It enables you to do command line development in OS X. It consists of two components like command line tools such as Clang and OS X SDK.


Mention what is the use of PO command in Xcode?
PO command is useful during debug time. In normal scenario, to print the value of a variable, you have to move the mouse pointer there and select print description print value of it. With PO command, you can print value by just writing the “PO variable name” in output window, and press enter.


What is Objective c?
Objective-C is reflective, object-oriented programming language which adds Smalltalk-style messaging to the C programming language. strictly superset of c.


What is Swift?
Swift is a programming language for development of applications for OS X, iOS, watchOS, and tvOS. These applications are developed using C and Objective-C. It does not have the constraints of C Programming. It has features for easier development and provides more flexibility.


Explain xib?
.xib is a file extension that is associated with Interface Builder files. It is a graphics software that is used to test, develop and design the User Interfaces of different software products. Such extension files also contains development time format files that includes interface files created with interface builder softwares.


What is storyboard?
With Storyboards, all screens are stored in a single file. This gives you a conceptual overview of the visual representation for the app and shows you how the screens are connected. Xcode provides a built-in editor to layout the Storyboards.


What is Auto Layout?
Auto Layout is a new way to define dynamic GUIs. Before, we had autoresizing masks, that described how a subview will resize or move when its superview is resized. With Auto Layout you can do the same and also a lot more complicated GUIs quite easily.
Auto Layout dynamically calculates the size and position of all the views in your view hierarchy, based on constraints placed on those views.


What is the difference between frame and bounds?
The frame of a view is the rectangle, expressed as a location (x, y) and size (width, height) relative to the superview it is contained within. The bounds of a view is the rectangle, expressed as a location (x, y) and size (width, height) relative to its own coordinate system (0,0).


What are the ViewController lifecycle in ios?
viewDidLoad – viewWillAppear - viewDidAppear - viewDisappear – viewDidUnload


What is the difference between viewDidLoad and viewDidAppear?
viewDidLoad is called when the view is loaded, whether from a Xib file, storyboard or programmatically created in loadView. viewDidAppear is called every time the view is presented on the device. Which to use depends on the use case for your data. If the data is fairly static and not likely to change then it can be loaded in viewDidLoad and cached. However if the data changes regularly then using viewDidAppear to load it is better. In both situations, the data should be loaded asynchronously on a background thread to avoid blocking the UI.


Tell me about the MVC architecture? (M-Model, V-View, C-Controller)
Main advantage of MVC architecture is to provide “reusability and security” by separating the layer by using MVC architecture.
Model: it is a class model is interact with database.
Controller: controller is used for by getting the data from model and controls the views.
View: Display the information in views.


What is an Object?
Objects are essentially the variables that are of Class types. Objects are basic Run-Time entities in an Object oriented system. It represents a place, a bank account or a person.


What is a Class?
The entire set of data of an object can be made a user-defined data type using a class. Objects are basically variables of Class type. Once a Class has been defined, it is possible to create multiple Objects of its type. A Class is a collection of Objects of similar type.


Explain Inheritance?
Inheritance is an Object Oriented Programming concept. It allows develop a New Class that is reusable and can extend the behaviour that is defined in another class.


What is data encapsulation?
Data is contained within objects and is not accessible by any other than via methods defined on the class is called data encapsulation.


Explain the difference between Inheritance and Category?
Category enables to add methods only. It does not allow the inclusion of Data Members unlike Inheritance where both the Data and Methods can be added.
Category includes Complete Application in its Scope whereas Inheritance scope is only within that particular File.


What is "private", "Protected" and "Public" ?
private - limits the scope class variable to the class that declares it.
protected - Limits instance variable scope to declaring and inheriting classes.
public - Removes restrictions on the scope of instance variables


What is a Collection?
A Collection is a Foundation Framework Class that is used to Manage and Store the group of Objects. The primary role of a Collection is to store Objects in the form of either a Set, a Dictionary or an Array.


What is Garbage Collection?
Garbage Collection is a Memory Management feature. It manages the allocation and release of the memory to your applications. When the garbage collector performs a collection, it checks for objects in the managed heap that are not executed by the applications.


Explain Fast Enumeration?
Fast enumeration is a iOS Programming Language feature that enables you to enumerate over the contents of a collection. It will also make your code execute your code faster due to internal implementation which gets reduced message sending overheads and increased pipelining potential.
for(id object in objets) {
}


What is Singleton Class?
Singleton defines a one instance shared across the entire app.
A Singleton is special kind of class where only one instance of the class exists from current process.


What is Delegate?
Delegate is an object that has been assigned by another object. The object is responsible for handling events. It’s useful tool for communicating b/w objects.
Delegates are a design pattern. A delegate is an object that will respond to pre-chosen selectors, need to implement the protocol method by the delegate object.


What is Protocol on objective c?
A protocol declares methods that can be implemented by any class. Protocols are not classes themselves. They simply define an interface that other objects are responsible for implementing. The idea is to provide a way for classes to share the same method and property declarations without inheriting them from a common ancestor.


What is Category in Objective c?
A category allows you to add methods to an existing class—even to one for which you do not have the source.


What is the "interface" and "implementation"?
Interface declares the behaviour of class.
Implementation defines the behaviour of class.


Major differences between Structures and Classes?
Structures
Classes
  • Struct is value type. 
  • Cannot inherit from other struct.
  • It has free initialiser for you , you don’t have to declare initialiser if you do free initialiser will be overwritten by your declared initialiser.
  • don’t have de-initialiser.
  • Class is reference type.
  • Can inherit from other classes.
  • Must declare initialiser (constructer).
  • Has de-initialisers.

Explain KVC and KVO?
Key-Value-Coding (KVC) means accessing a property or value using a string. 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.
id someValue = [myObject valueForKeyPath:@"foo.bar.baz"];
id someValue = [[[myObject foo] bar] baz];
Key-Value-Observing (KVO) allows you to observe changes to a property or value. To observe a property using KVO you would identify to property with a string; i.e., using KVC. Therefore, the observable object must be KVC compliant.
[myObject addObserver:self forKeyPath:@"foo.bar.baz" options:0 context:NULL];


What is Notification?
Notification provides a mechanism for broadcasting information within a program, using notification we can send message to other object by adding observer.
UILocalNotification represents notifications are scheduled for presentation to the user at specific date and time. Displayed alerts and playing sounds are composed and deliver locally.


What is application document directory?
Each application is restricted in terms of where it can be stored data on the file system of device. The iOS application are allows to read and write to their own documents and temp directories.
The Foundation.framework three class that are working with files and directories
  • NSFileManager - The NSFileManager class is typically your primary mode of interaction with the file system. You use it to locate, create, copy, and move files and directories. You also use it to get information about a file or directory or change some of its attributes.
  • NSFileHandle – It is provided for performing low level operation on file. Reading and Writing a file contents specified by a specified number of bytes and appending data to an existing file.
  • NSData – It is provides useful storage buffer into which the contents file or which dynamically store data into file. NSData is typically used for data storage and copied or moved b/w applications.

What is synchronous web request and asynchronous?
In synchronous request main thread gets block and control will not get back to user till that request gets execute.
In Asynchronous control gets back to user even if request is getting execute.


Explain Mutable and Immutable Types in Objective C Programming Language?
Mutable Types means you can modify the Contents later when you feel the need. However, when an Object is marked as Immutable, it implies that the data cannot be modified later after it has been initialized. Therefore, the stored values are Constant here.
Example: NSString, NSArray values cannot be altered after initialization.


How many different ways to pass data in Swift ?
There are many different ways such as Delegate, KVO, Segue, and NSNotification, Target-Action, Callbacks.

What is Memory Management?
The memory Management environment to ensure your app doesn’t leak memory or try to reference objects that are no longer exists.
  1. MRR – Manual Retain Release Method
  2. ARC – Automatic Reference Counting Method


Explain MRR?
Dealing with memory behinds the objects property. In this method manually control the object allocation and de-allocation. The object have to every “alloc”, “retain” and “copy” to call with a “release” or “autorelease”.


Explain ARC?
ARC represents Automatic Reference Counting. It is a Compiler level feature that simplifies the process of managing the lifetimes of Objects in Objective – C. ARC evaluates the Lifetime requirements of Objects and automatically includes appropriate Methods to be called during Compilation.


What manual memory management? how it work?
In Manual memory management developers is responsible for life cycle of object. developer has to retain /alloc and release the object wherever needed.


How to find the memory leaks in MRC?
By using -
    1. Static Analyser.
    2. Instrument

What is a memory leak?
A memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in such a way that memory which is no longer needed is not released. In object-oriented programming, a memory leak may happen when an object is stored in memory but cannot be accessed by the running code.


Difference between nil and Nil?
Nil is meant for class pointers, and nil is meant for object pointers


Difference between release and autorelease?
release - destroy the object from memory,
autorelease - destroy the object from memory in future when it is not in use.


Explain keywords ‘alloc’ and ‘new’?
The alloc keyword is used to create a New Memory Location in the System. However, it does not initialize it. In case of New keyword, it also helps to create a New Memory Location in the system. However, it can initialize the Contents unlike the alloc keyword.


What is property in Objective c?
Property allow declared variables with specification like atomic/nonatomic, or retain/assign


What is meaning of "synthesize" keyword?
ask the compiler to generate the setter and getter methods according to the specification in the declaration


What is the use of "dynamic" keyword?
Instructs the compiler not to generate a warning if it cannot find implementations of accessor methods associated with the properties whose names follow.


What is the meaning of "strong" keyword?
strong -o "own" the object you are referencing with this property/variable. The complier with be responsible for lifetime of object which is declared as strong.


What is the meaning of "weak" keyword?
Weak - weak reference you signify that you don't want to have control over the object's lifetime. The compiler will destroy object once strong reference that hold weak object get destroyed.


What is meaning of "atomic" keyword?
"atomic", the synthesized setter/getter will ensure that a whole value is always returned from the getter or set by the setter, only single thread can access variable to get or set value at a time


What is meaning of "nonatomic" keyword?
In non atomic no such guaranty that value is returned from variable is same that setter sets. at same time


What is meaning of "retain" keyword?
Specifies that retain should be invoked on the object upon assignment. takes ownership of an object


What is meaning of "assign" keyword?
Specifies that the setter uses simple assignment. Uses on attribute of scalar type like float,int.


What is meaning of "copy" keyword?
copy object during assignment and increases retain count by 1


What is meaning of "readOnly" keyword?
Declare read only object / declare only getter method


What is the difference between let and var in Swift?
The let keyword is used to declare constants while var is used for declaring variables.
let someConstant = 10
var someVariable : String


What is the difference ANY and ANYOBJECT ?
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.


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


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


What is the use of double question marks (??) ?
To provide a default value for a variable.
let missingName : String? = nil
let realName : String? = “John Doe"
let existentName : String = missingName ?? realName


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


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


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


What are optional binding and optional chaining in Swift?
Optional Chaining is a process of querying and calling properties. Multiple queries can be chained together, and if any link in the chain is nil then, the entire chain fails.
class School {
var director:Person?
}
class Person {
var name: String = ""
init(name: String) {
self.name = name
}
}
var school = School()
var person = Person(name: "Jason")
school.director = person
school.director?.name

Optional Binding is a term used when you assign temporary variables from optionals in the first clause of an if or while block. Consider the code block below when the property courses have yet not been initialized. Instead of returning a runtime error, the block will gracefully continue execution.
var myString:String?
myString = "Hello, Swift!"
if let yourString = myString {
println("Your string has - \(yourString)")
}else {
println("Your string does not have a value")
}


What is a deinitializer in Swift?
If you need to perform additional cleanup of your custom classes, it's possible to define a block called deinit. The syntax is the following:
deinit {
//Your statements for cleanup here
}


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


What are the benefits of Swift over Objective-C ?
Swift is easier to read, maintain and It’s Safe. It’s unified with memory management. Swift requires less code and It’s faster. Swift support dynamic libraries.


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


Explain what is Swift Programming Language?
Swift is a programming language and system for creating applications for iOS and OS X. It is an innovative programming language for Cocoa and Cocoa Touch.


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


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

What is the difference between NSArray and NSMutableArray?
NSArrayʼs contents cannot be modified once itʼs been created whereas a NSMutableArray can be modified as needed, i.e items can be added/removed from it.


What are Selectors in Objective-C?
A Selector in Objective C can be used to refer the name of a method when it is used in a Source-Code message to an Object. It also refers to the unique identifiers that can replace the Name when the Source Code is being Compiled. All the methods that have the same name have the same selector.


What mechanisms does iOS provide to support multi-threading?
1. NSThread creates a new low-level thread which can be started by calling the start method.
NSThread* myThread = [[NSThread alloc] initWithTarget:self
selector:@selector(myThreadMainMethod:)
object:nil];
[myThread start];

2. NSOperationQueue allows a pool of threads to be created and used to execute NSOperations in parallel. NSOperations can also be run on the main thread by asking NSOperationQueue for the mainQueue.
NSOperationQueue* myQueue = [[NSOperationQueue alloc] init];
[myQueue addOperation:anOperation];
[myQueue addOperationWithBlock:^{
/* Do something. */
}];

3. GCD or Grand Central Dispatch is a modern feature of Objective-C that provides a rich set of methods and API's to use in order to support common multi-threading tasks. GCD provides a way to queue tasks for dispatch on either the main thread, a concurrent queue (tasks are run in parallel) or a serial queue (tasks are run in FIFO order).
dispatch_queue_t myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(myQueue, ^{
printf("Do some work here.\n");
});


What are blocks and how are they used?
Blocks are a way of defining a single task or unit of behaviour 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");
}
myBlock();


What is use of NSOperation? how NSOperationque works?
An operation object is a single-shot object. It executes its task once and cannot be used to execute it again. You typically execute operations by adding them to an operation queue. An NSOperationQueue object is a queue that handles objects of the NSOperation class type. An NSOperation object, simply phrased, represents a single task, including both the data and the code related to the task. The NSOperationQueue handles and manages the execution of all the NSOperation objects that have been added to it.


How to start a thread?
- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg on NSObject
NSThread* evtThread = [[NSThread alloc] initWithTarget:self selector:@selector(saySomething) object:nil];
[evtThread start];


What is GCD? How is it used?
GCD is the most commonly used API to manage concurrent code and execute operations asynchronously at the Unix level of the system. GCD provides and manages queues of tasks. Example is when an App fetch data from an API, this network call should be done in a background thread and the display of the data in view should be executed in the main thread as well as any UI updates.


What is "Push Notification"?
To get the any update /alert from server.


What is the Maximum byte-size for a push notification to Apple Server?
The maximum memory size is 256 Bytes to send a push Notification to Apple Server


How to use reusable cell in UITableview?
By using dequeReusableCellWithIdentifier


Core Data – Definition?
It is an object graph and persistence framework. Core data handles the data model. It’s relational entity attribute model.


SQLite – Definition?
It is an relational database management system contained c programming library. It’s used by syntax.


How to deal with SQLite database?
Dealing with sqlite database in iOS:
1. Create database : sqlite3 AnimalDatabase.sql
2. Create table and insert data into table :
CREATE TABLE animals ( id INTEGER PRIMARY KEY, name VARCHAR(50), description TEXT, image VARCHAR(255) );
INSERT INTO animals (name, description, image) VALUES ('Elephant', 'The elephant is a very large animal that lives in Africa and Asia', 'http://dblog.com.au/wp-content/elephant.jpg');
3. Create new app --> Add SQLite framework and database file to project
4. Read the database and close it once work done with database :
// Setup the database object
sqlite3 *database;
// Init the animals Array
animals = [[NSMutableArray alloc] init];
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = "select * from animals";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *aDescription = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *aImageUrl = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
// Create a new animal object with the data from the database
Animal *animal = [[Animal alloc] initWithName:aName description:aDescription url:aImageUrl];
// Add the animal object to the animals Array
[animals addObject:animal];
[animal release];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);


Explain Web Services?
The Web Services are the Application Components which enables communication using Open Protocols. Web Services can be found out by using UDDI. The base for development of Web Services functionality is Extensible Markup Language (XML).


How to parse JSON? Explain in deep?
By using NSJSONSerialization.
Example: NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &err];


Please explain SOAP and REST Basics differences ?
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.
REST ( Representational State Transfer ) provides a lighter weight alternative. Instead of using XML to make a request, REST relies on a simple URL in many cases. REST can use four different HTTP 1.1 verbs (GET, POST, PUT, and DELETE) to perform tasks.


How to parse xml? Explain in deep?
Using NSXMLParser.
Create xml parser object with xml data, set its delegate , and call the parse method with parserObject.
Delegate methods
– parserDidStartDocument:
– parserDidEndDocument:
– parser:didStartElement:namespaceURI:qualifiedName:attributes:
– parser:didEndElement:namespaceURI:qualifiedName:
– parser:didStartMappingPrefix:toURI:
– parser:didEndMappingPrefix:
– parser:resolveExternalEntityName:systemID:
– parser:parseErrorOccurred:
– parser:validationErrorOccurred:
– parser:foundCharacters:
– parser:foundIgnorableWhitespace:
– parser:foundProcessingInstructionWithTarget:data:
– parser:foundComment:
– parser:foundCDATA:


Difference between SAX parser and DOM parser?
SAX (Simple API for XML)
-Parses node by node
-Doesn't store the XML in memory.
-We cannot insert delete a node
-Top to bottom traversing
DOM (Document Object Model)
-Stores the entire XML document into memory before processing
-Occupies more memory
-We can insert or delete nodes
-Traverse in any direction

What is the UITableViewDelegate?
It is a protocol. Table View object adopt with the “delegate” protocol. The protocol allow the methods are Manage selection, configure header and footer section, delete the cell and reload the cells.


What is the UITableViewDataSource?
The UITableViewDataSource protocol is adopted by an object that mediates the application’™s data model for a UITableView object. The data source provides the table-view object with the information it needs to construct and modify a table view.


UITableView DataSource
– tableView:cellForRowAtIndexPath: required method
– numberOfSectionsInTableView:
– tableView:numberOfRowsInSection: required method
– sectionIndexTitlesForTableView:
– tableView:sectionForSectionIndexTitle:atIndex:
– tableView:titleForHeaderInSection:
– tableView:titleForFooterInSection:
– tableView:commitEditingStyle:forRowAtIndexPath:
– tableView:canEditRowAtIndexPath:
– tableView:canMoveRowAtIndexPath:
– tableView:moveRowAtIndexPath:toIndexPath:


UITableView Delegate
– tableView:heightForRowAtIndexPath:
– tableView:indentationLevelForRowAtIndexPath:
– tableView:willDisplayCell:forRowAtIndexPath:
– tableView:accessoryButtonTappedForRowWithIndexPath:
– tableView:willSelectRowAtIndexPath:
– tableView:didSelectRowAtIndexPath:
– tableView:willDeselectRowAtIndexPath:
– tableView:didDeselectRowAtIndexPath:
– tableView:viewForHeaderInSection:
– tableView:viewForFooterInSection:
– tableView:heightForHeaderInSection:
– tableView:heightForFooterInSection:
– tableView:willBeginEditingRowAtIndexPath:
– tableView:didEndEditingRowAtIndexPath:
– tableView:editingStyleForRowAtIndexPath:
– tableView:titleForDeleteConfirmationButtonForRowAtIndexPath:
– tableView:shouldIndentWhileEditingRowAtIndexPath:
– tableView:targetIndexPathForMoveFromRowAtIndexPath: toProposedIndexPath:
– tableView:shouldShowMenuForRowAtIndexPath:
– tableView:canPerformAction:forRowAtIndexPath:withSender:
– tableView:performAction:forRowAtIndexPath:withSender:


UITextFeild-Delegates
– textFieldShouldBeginEditing:
– textFieldDidBeginEditing:
– textFieldShouldEndEditing:
– textFieldDidEndEditing:
– textField:shouldChangeCharactersInRange:replacementString:
– textFieldShouldReturn:


UITextView-Delegates
– textViewShouldBeginEditing:
– textViewDidBeginEditing:
– textViewShouldEndEditing:
– textViewDidEndEditing:
– textView:shouldChangeTextInRange:replacementText:
– textViewDidChange:
– textViewDidChangeSelection:


UIPickerView DataSource
– numberOfComponentsInPickerView:
– pickerView:numberOfRowsInComponent:
UIPickerView Delegate
– pickerView:rowHeightForComponent:
– pickerView:widthForComponent:
– pickerView:titleForRow:forComponent:
– pickerView:viewForRow:forComponent:reusingView:
– pickerView:didSelectRow:inComponent:


MKMapView Delegate
Responding to Map Position Changes
– mapView:regionWillChangeAnimated:
– mapView:regionDidChangeAnimated:
Loading the Map Data
– mapViewWillStartLoadingMap:
– mapViewDidFinishLoadingMap:
– mapViewDidFailLoadingMap:withError:
Tracking the User Location
– mapViewWillStartLocatingUser:
– mapViewDidStopLocatingUser:
– mapView:didUpdateUserLocation:
– mapView:didFailToLocateUserWithError:
– mapView:didChangeUserTrackingMode:animated: required method
Managing Annotation Views
– mapView:viewForAnnotation:
– mapView:didAddAnnotationViews:
– mapView:annotationView:calloutAccessoryControlTapped:
Dragging an Annotation View
– mapView:annotationView:didChangeDragState:fromOldState:
Selecting Annotation Views
– mapView:didSelectAnnotationView:
– mapView:didDeselectAnnotationView:
Managing Overlay Views
– mapView:viewForOverlay:
– mapView:didAddOverlayViews:


Explain the steps involved in submitting the App to App-Store?
Enroll in Program—>Provision Devices—>Create iTunes Record->Submit App->Ship App


What is Bundle ID?
The Bundle ID uniquely defines every iOS Application. It is specified in Xcode. It is a Search String which is supplied by the Application Developer to match either the Bundle ID of a Single Application or a Set of Bundle IDs for a Group of Applications.


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


Explain IPA?
IPA represents iOS App Store Package. It has an .ipa extension which represents iPhone application archive file that stores an iPhone application. Every file is compressed with a Binary for the ARM architecture and can only be installed on an iPhone, ipad or an iPod Touch. It is mostly encrypted with Apple’s FairPlay DRM Technology.


Explain plist?
Plist represents Property Lists. It is a key-value store for the Application to Save and Retrieve persistent data values. This is specifically used for iPhone development. It is basically and XML File.