Search Your Question

In Objective C, how can avoid crashing of app?

Ans. :

There are multiple aspects to your questions, let me try to answer them:

  • NSSetUncaughtExceptionHandler only catches uncaught exceptions which is only a small subset of possible crashes. 
  • Exceptions in Objective-C are defined to be fatal and it is not recommended to catch them and even more not recommended to run any non-async safe code, which includes any Objective-C and Swift code. 
  • To catch crashes you need to setup signal handlers and then only run async-safe code at the time of the crash, which is only a small subset of C. Especially you may not allocate new memory at crash time at all.

signal(SIGABRT, SignalHandler);
signal(SIGILL, SignalHandler);
signal(SIGSEGV, SignalHandler);
signal(SIGFPE, SignalHandler);
signal(SIGBUS, SignalHandler);
signal(SIGPIPE, SignalHandler);

This will works for most situations.

Difference between objective c and swift protocol


Protocol in Objective-C has optional methods and Protocol in Swift has all required methods to implement.

In Swift, Protocol extension is introduced and due to it swift is called protocol oriented language.

Read Protocol Extension to know difference between objective-c and swift protocol

Write a program to define closure, which take string, return integer

Ans : 

Write a closure that accepts string and return length of string :

 let simpleClosure:(String) -> (Int) = { name in
     return name.count

 let result = simpleClosure("Hello, World")


What is NSNotification?

Ans :  Apple has provided an Observer Pattern in the Cocoa library called the NSNotificationCenter.

The basic idea is that a listener registers with a broadcaster using some predefined protocol. At some later point, the broadcaster is told to notify all of its listeners, where it calls some function on each of its listeners and passes certain arguments along. This allows for asynchronous message passing between two different objects that don't have to know about one-another, they just have to know about the broadcaster.

NSNotification is like notifying the other class about the changes that will happen if some action takes place in another class.

Simple :

NSNotificationCenter can be thought of as a broadcaster and we can tune into different stations, or channels to listen for any changes.

Example : 

NotificationCenter.default is where all notifications are posted to and are observed from. Each notification must have a unique way to identify themselves. If we were to observe, or listen, to any channel, we would call on the observe method available to us through NotificationCenter.default and perform some type of action based on this listening.

We have two view controllers named VC1 and VC2. We having observer in VC1 and when we select something in VC2, VC2 post notifications to observer methods.

VC1 :

 func setToIndia(notification: NSNotification) {
     cityChosenLabel.text = "India"
 func setToPakistan(notfication: NSNotification) {
     cityChosenLabel.text = "Pakistan"


Now, we create extension to set unique name to notification.

 extension Notification.Name {
     static let india = Notification.Name("India")
     static let  pakistan = Notification.Name("Pakistan")

Now we add observer methods,

 NotificationCenter.default.addObserver(self, selector:   #selector(setToIndia(notification:)), name: .india, object: nil)

 NotificationCenter.default.addObserver(self, selector:  #selector(setToPakistan(notfication:)), name: .pakistan, object: nil)


We will post notification on selecting something here :

 @IBAction func indiaButton(_ sender: Any) { .india, object: nil)

 @IBAction func pakistanButton(_ sender: Any) { .pakistan, object: nil

* When indaButton clicked, Notification Center broadcast notification with message to all listeners name India. 

If you didn't understand still, consider notification center is radio station and our mobile device has observer methods so it can listen radio station's voice.


Different types of Control statements.


Control flow statements are used to control the flow of execution in a program.

1. Loop Statement : 


let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
    print("Hello, \(name)!")


var i:Int = 0
while i < 10 {
    i += 1

var j: Int = 10
repeat {
while(j < 10)

2. Branch Statement : 

var numArray = [10, 20, 30, 40, 50, 60, 70]
    print("true it contains 20")
    print("number is not there")

guard condition else {

The else clause of a guard statement is required, and must either call a function with the Never return type or transfer program control outside the guard statement’s enclosing scope using one of the following statements:  
  • return 
  • break 
  • continue
  •  throw
switch grade {
case 90 ..< 100:
case (80 ..< 90):
case (70 ..< 80):
case (0 ..< 70):
    print("F. You failed")//Any number less than 0 or greater than 99

3. Control Transfer Statement : 
let numbersArray = [20, 30, 40, 50, 60, 70, 80, 90, 10]
for num in numbersArray{
    if(num > 10){

// prints: 10

let numbersArray = [20, 30, 40, 50, 60, 70, 80, 90, 10]
for num in numbersArray{
    if num > 30{

fallthrough : switch statements don’t fallthrough the bottom of each case and into the next one. That is, the entire switch statement completes its execution as soon as the first matching case is completed.

for num in numbersArray{
    switch num {
    case 10:
    case 20:
    case 30:
    case 40:
        print("nothing here")

return :
func myFunc() -> Int {
    let myNumber = 16 % 3
    if myNumber == 0 {
        return 0
    else if myNumber == 1 {
        return 1
    return 0

enum ErrorsToThrow: Error {
    case fileNotFound
    case fileNotReadable
    case fileSizeIsTooHigh
class documents {
    init() {
        do {
            let dataFromString = try? readFiles(path: "")
        } catch ErrorsToThrow.fileNotFound {
            print("error generated1")
        } catch ErrorsToThrow.fileNotReadable {
            print("error generated2")
        } catch ErrorsToThrow.fileSizeIsTooHigh {
            print("error generated3")
        } catch {
func readFiles(path:String) throws  ->String {
        if path == "" {
            throw ErrorsToThrow.fileNotFound
        return "Data from file"