Search Your Question

How can we store object in user default?

Ans : 

Actually, you will need to archive the custom object into NSData then save it to user defaults and retrieve it from user defaults and unarchive it again. You can archive it like this
let teams = [Team(id: 1, name: "team1", shortname: "t1"), Team(id: 2, name: "team2", shortname: "t2")]

var userDefaults = UserDefaults.standard
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: teams)
userDefaults.set(encodedData, forKey: "teams")
userDefaults.synchronize()
and unarchive it like this
let decoded  = userDefaults.data(forKey: "teams")
let decodedTeams = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! [Team]
But if you just did that you will get
.Team encodeWithCoder:]: unrecognized selector sent to instance
You will have to make Team conform to NSCoding just like this
class Team: NSObject, NSCoding {
    var id: Int
    var name: String
    var shortname: String


    init(id: Int, name: String, shortname: String) {
        self.id = id
        self.name = name
        self.shortname = shortname

    }

    required convenience init(coder aDecoder: NSCoder) {
        let id = aDecoder.decodeInteger(forKey: "id")
        let name = aDecoder.decodeObject(forKey: "name") as! String
        let shortname = aDecoder.decodeObject(forKey: "shortname") as! String
        self.init(id: id, name: name, shortname: shortname)
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(id, forKey: "id")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(shortname, forKey: "shortname")
    
}



Difference between network location and gps location.

Ans : 

Network location usually refers to cellular location, or wifi location. They are less accurate then GPS (Global Positioning System - satellite based) location. When the app cannot obtain GPS location (probably because the target device is inside a building), the less accurate network location is obtained and uploaded to the map page.



Which method called when I click on next, done button of keyboard?

Ans : textFieldShouldReturn


func textFieldShouldReturn(_ textField: UITextField) -> Bool {
     return false
}

What are UITextField delegate methods?

Ans : 

Copy from Apple Developer Site : Link


Managing Editing

func textFieldShouldBeginEditing(UITextField) -> Bool
Asks the delegate if editing should begin in the specified text field.
func textFieldDidBeginEditing(UITextField)
Tells the delegate that editing began in the specified text field.
func textFieldShouldEndEditing(UITextField) -> Bool
Asks the delegate if editing should stop in the specified text field. 
func textFieldDidEndEditing(UITextField, reason: UITextField.DidEndEditingReason)
Tells the delegate that editing stopped for the specified text field.
func textFieldDidEndEditing(UITextField)
Tells the delegate that editing stopped for the specified text field.
enum UITextField.DidEndEditingReason
Constants indicating the reason why editing ended in a text field.

Editing the Text Field’s Text

func textFieldShouldClear(UITextField) -> Bool
Asks the delegate if the text field’s current contents should be removed.
func textFieldShouldReturn(UITextField) -> Bool
Asks the delegate if the text field should process the pressing of the return button.

What is NSZombie?

Ans : 

It's a memory debugging aid. Specifically, when you set NSZombieEnabled then whenever an object reaches retain count 0, rather than being deallocated it morphs itself into an NSZombie instance. Whenever such a zombie receives a message, it logs a warning rather than crashing or behaving in an unpredictable way. As such, you can debug subtle over-release/autorelease problems without advanced tools or painstaking needle in haystack searches.

The name is a fairly obvious play on the fact that objects are normally considered "dead" when they reach retain count 0. With this setting, they continue to exist in a strange half-life - neither living, nor quite dead. Much like real zombies, except they eat rather fewer brains.


Enlist different background modes

Ans : 

There are different background modes provided from apple and we can see them under Signing & Capabilities > + Capability (New) > Background Mode

Switch on background mode and select which is required in our project.

Background Modes in iOS



  1. Audio, AirPlay and Picture in Picture
  2. Location updates
  3. Void over IP
  4. External accessory communication
  5. Uses Bluetooth LE accessories
  6. Acts as a Bluetooth LE accessory
  7. Background fetch
  8. Remote notifications
  9. Background processing


For tutorial, I recommended raywanderlich.com article 

Does swift supports method overloading?

Ans :  Yes. It supports method overloading.

Source : Programiz

Difference between KVO and KVC and Delegate

Ans : There is no way to find any differences between KVC and KVO. Both are different things.

1. KVC - Key Value Coding

We can get and set value of class property using string.

Code for example :

import UIKit

class Employee : NSObject {
    @objc var name = String()
    @objc var age = 0
    @objc var assets = ["ID Card", "Macbook"]

}

We should make sure that Employee inherits from NSObject because it confirms protocol named NSKeyValueCodiing.

We also make sure that @objc should be added as it is objective c runtime for making those properties available for coding. emp.setValue("Manna", forKeyPath: #keyPath(<#T##@objc property sequence#>))

Using KVC,
let emp = Employee()
emp.setValue("Manan", forKey: "name")

Here, we set value of name property using string "name". Here there is chance to misspell property name.

Another way,

emp.setValue("Manna", forKeyPath: #keyPath(Employee.name))

Benefit of this way,  There is no any chance to misspell as it only accepts valid key path other wise it gives compile time error.

Another way,

emp.setValuesForKeys([
                        "name" : "Manan",
                        "age"  : 29

                ])

What will happened, if we have some private properties in class. They are not accessible directly using their value. We have to make extension of class to use their values.
or

@objc private var name = String()

emp.setValue("Manan", forKey: "name")
emp.value(forKey: "name")

We can access private properties as above using KVC. emp.name will give compile time error as name is private,  but using KVC it is possible to access.

We can access array and add item in this array,

let mutableArray = emp.mutableArrayValue(forKeyPath: #keyPath(Employee.assets))
mutableArray.add("Laptop Bag")


2. KVO - Key value observer

When we want to do something when property values changes, we can use KVO concept. We can observer property and on value changed we can take action.

For that,
A special method named observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) should be implemented to the observing class.


self.child1.addObserver(self, forKeyPath: "name",  optional: [.new, .old], context: child1context]


There are some parameters :

  • addObserver:  This is the observing class, usually the self object. 
  • forKeyPath: I guess you can understand what’s this for. It is the string you used as a key or a key path and matches to the property you want to observe. Note that you specify here either a single key, or a key path. 
  • options: an array of NSKeyValueObservingOptions values. 
  • context: This is a pointer that can be used as a unique identifier for the change of the property we observe. Usually this is set to nil or NULL. We’ll see more about this later.
We have to implement  following observerValue method and it is mandatory to adopt KVO concept.




Sometimes, we don't want notification when some  property value changed. Then we do following :


Credit : HackerMoon

Know more about KVO : Click here

Difference between Delegate, Notification and KVO


Use a delegate if you want to talk to only one object. For example, a tableView has a delegate - only one object should be responsible for dealing with it.

Use notifications if you want to tell everyone that something has happened. For example in low memory situations, a notification is sent telling your app that there has been a memory warning. Because lots of objects in your app might want to lower their memory usage it's a notification.

I don't think KVO is a good idea at all and try not to use it but, if you want to find out if a property has changed you can listen for changes.

What is entry point of iOS Application?

Ans : 

In mostly language, There is having main method in main file which is starting point of project. In iOS, also same approach are there.

Objective-C :

main.m File :

int main(int argc, char * argv[]) {
        NSString * appDelegateClassName;
        @autoreleasepool {
            // Setup code that might create autoreleased objects goes here.
            appDelegateClassName = NSStringFromClass([AppDelegate class]);
        }
        return UIApplicationMain(argc, argv, nil, appDelegateClassName);
        
        

    }

Swift : 

AppDelegate.swift

import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {




In Swift, @UIApplicationMain attribute is a replacement of main.m file & and entry point for your application to start.


Meaning of ??, !!, !?, ?!

Ans : 

1. ?? is  Nil-Coalescing Operator. It is used to provide default value if value is nil.

let val = values["value1"] as? String ?? "default"

2. !!

i.e
struct StockFullData: Codable
{  
           var ok : Bool?  
           var sn : StockName?
}

struct StockName : Codable
{  
           let display_name : String?
}

Now Check :

print(s.sn?.display_name)      
print((s.sn?.display_name!))      
print((s.sn?.display_name!)!)      
 print((s.sn!.display_name!))

Output :

Optional("m")
Optional("m")
m
m

-> See third print, where we have used !! for extract value. I am not sure it is correct answer because it is like !)! .

3. !? : am finding answer or We can make custom operator using this .
4. ?! : am finding answer or We can make custom operator using this .

If you have any comment, question, or recommendation, feel free to post them in the comment section below!