Search Your Question

Showing posts with label Saint Gobain. Show all posts
Showing posts with label Saint Gobain. Show all posts

UITableviewDelegate and UITableViewDataSource Methods

Ans : 

UITableview's Delegate Methods :

The UIViewController in which UITableView you use must adopt the UITableViewDelegate protocol. Optional methods of the protocol allow the delegate to manage selections, configure section headings and footers, help to delete and reorder cells, and perform other actions.

Configuring Rows for the Table View

- tableView:heightForRowAtIndexPath:
- tableView:indentationLevelForRowAtIndexPath:
- tableView:willDisplayCell:forRowAtIndexPath:

Managing Accessory Views

- tableView:accessoryButtonTappedForRowWithIndexPath:
- tableView:accessoryTypeForRowWithIndexPath: Deprecated in iOS 3.0

Managing Selections

- tableView:willSelectRowAtIndexPath:
- tableView:didSelectRowAtIndexPath:
- tableView:willDeselectRowAtIndexPath:
- tableView:didDeselectRowAtIndexPath:

Modifying the Header and Footer of Sections

- tableView:viewForHeaderInSection:
- tableView:viewForFooterInSection:
- tableView:heightForHeaderInSection:
- tableView:heightForFooterInSection:

Editing Table Rows

- tableView:willBeginEditingRowAtIndexPath:
- tableView:didEndEditingRowAtIndexPath:
- tableView:editingStyleForRowAtIndexPath:
- tableView:titleForDeleteConfirmationButtonForRowAtIndexPath:
- tableView:shouldIndentWhileEditingRowAtIndexPath:

Reordering Table Rows

- tableView:targetIndexPathForMoveFromRowAtIndexPath:toProposedIndexPath:

Copying and Pasting Row Content

- tableView:shouldShowMenuForRowAtIndexPath:
- tableView:canPerformAction:forRowAtIndexPath:withSender:
- tableView:performAction:forRowAtIndexPath:withSender: 

UITableview's Data Source Methods : The NSTableViewDataSource protocol declares the methods that an instance of NSTableView that provides the data to a table view and allows editing of the contents of its data source object.

All the methods are described in the following.

Getting Values

- numberOfRowsInTableView: (Required)
- numberOfSectionInTableView:
- cellForRowAtIndexPath : (Required)
- tableView:objectValueForTableColumn:row:

Setting Values

- tableView:setObjectValue:forTableColumn:row:

Implementing Pasteboard Support

- tableView:pasteboardWriterForRow:

Drag and Drop

- tableView:acceptDrop:row:dropOperation:
- tableView:namesOfPromisedFilesDroppedAtDestination:forDraggedRowsWithIndexes:
- tableView:validateDrop:proposedRow:proposedDropOperation:
- tableView:writeRowsWithIndexes:toPasteboard:
- tableView:draggingSession:willBeginAtPoint:forRowIndexes:
- tableView:updateDraggingItemsForDrag:
- tableView:draggingSession:endedAtPoint:operation:


- tableView:sortDescriptorsDidChange:

Tips : UITableViewDelegate has no any required methods.

What is p12 and pem file

Ans : 

p12 : .p12 is an alternate extension for what is generally referred to as a "PFX file", it's the combined format that holds the private key and certificate and is the format most modern signing utilities use. Same with alternate extensions are .PFX, .PKCS12 

pem : this is a container format that may include just the public certificate (such as with Apache installs, and CA certificate files /etc/ssl/certs), or may include an entire certificate chain including public key, private key, and root certificates. 

Convert from .p12 file to .pem file 

cdcd Desktop openssl pkcs12 -in pushcert.p12 -out pushcert.pem -nodes -clcerts

Class, Structs and Enum

Ans : 

Structs are value type, Class is reference type.
Structs are stored in stack, Class are stored in heap.

So, Structs are faster than class because of its memory management. (Read why stack allocation is more faster than heap)

Similarity between Class and Struct: 

Define properties to store values
Define methods to provide functionality
Be extended
Conform to protocols
Define intialisers
Define Subscripts to provide access to their variables

Only class can do:

Type casting
Define deinitialisers
Allow reference counting for multiple references.

When to use class and when to use struct?

--> When we want to maintain reference, then we should use class due to class is reference type. When not, we should use struct.


Here's an example with a class. Note how when the name is changed, the instance referenced by both variables is updated. Bob is now Sue, everywhere that Bob was ever referenced.

class SomeClass {
    var name: String
    init(name: String) { = name

var aClass = SomeClass(name: "Bob")
var bClass = aClass // aClass and bClass now reference the same instance! = "Sue"

println( // "Sue"
println( // "Sue"

And now with a struct we see that the values are copied and each variable keeps it's own set of values. When we set the name to Sue, the Bob struct in aStruct does not get changed.

struct SomeStruct {
    var name: String
    init(name: String) { = name

var aStruct = SomeStruct(name: "Bob")
var bStruct = aStruct // aStruct and bStruct are two structs with the same value! = "Sue"

println( // "Bob"
println( // "Sue"

So for representing a stateful complex entity, a class is awesome. But for values that are simply a measurement or bits of related data, a struct makes more sense so that you can easily copy them around and calculate with them or modify the values without fear of side effects.

Another theory for what to choose : 

Structs are preferable if they are relatively small and copiable because copying is way safer than having multiple references to the same instance as happens with classes. This is especially important when passing around a variable to many classes and/or in a multithreaded environment. If you can always send a copy of your variable to other places, you never have to worry about that other place changing the value of your variable underneath you.

With Structs, there is much less need to worry about memory leaks or multiple threads racing to access/modify a single instance of a variable. (For the more technically minded, the exception to that is when capturing a struct inside a closure because then it is actually capturing a reference to the instance unless you explicitly mark it to be copied).

Classes can also become bloated because a class can only inherit from a single superclass. That encourages us to create huge superclasses that encompass many different abilities that are only loosely related. Using protocols, especially with protocol extensions where you can provide implementations to protocols, allows you to eliminate the need for classes to achieve this sort of behavior.

The talk lays out these scenarios where classes are preferred:
  • Copying or comparing instances doesn't make sense (e.g., Window)
  • Instance lifetime is tied to external effects (e.g., TemporaryFile)
  • Instances are just "sinks"--write-only conduits to external state (e.g.CGContext)

Optional, Optional Binding, Unwrapping and Optional Chaining

Ans : 

Optional : Optional is swift's powerful feature which come to solve problem of  non-existing value. It is just a type . There are two types as Int (which must has a value) and Int?(which may contain a Int value or may have nil value). It is declared as T? i.e Int?, String?

Forced Unwrapping : Exclamation mark ( ! ) is used to unwrap value.
i.e let optionalInt : Int? = 5
let intVal : Int = 2
optionalInt! + intVal

So we hvae forecfully unwrap optionaInt. That means we tell compiler that optionalInt has a value and extract and use it.

But this is not good practise. If sometimes optionaInt has not value and we try to unwrap, then app will be crashed. A good practise is to check with nil before unwrapping or use optional binding. It checks it has value or not and if and only if it has value extract it and use it.

Optional Binding : You use optional binding to check if the optional contains a value or not. If it does contain a value, unwrap it and put it into a temporary constant or variable.

Example :

var stockCode:String? = findStockCode("Facebook")

let text = "Stock Code - "

if let tempStockCode = stockCode {

    let message = text + tempStockCode


The “if let” (or “if var”) are the two keywords of optional binding. In plain English, the code says “If stockCode contains a value, unwrap it, set its value to tempStockCode and execute the conditional block. Otherwise, just skip it the block”. As the tempStockCode is a new constant, you no longer need to use the ! suffix to access its value.

Implicitly Unwrapped Optional : When we are very very sure about it has value after first time it is set, then we need not unwrap every time. So for this type of scenario, we have to use it with ! mark in their type.

// forced unwrapping
let optionalInt: Int? = 123
let forcedInt: Int = optionalInt!

// implicitly unwrapped optional
let assumedInt: Int! = 123
let implicitInt: Int = assumedInt

It may has nil value.

Optional Chaining :

The feature allows us to chain multiple optionals together with the “?.” operator.

if let sharePrice = findStockCode("Apple")?.price {

    let totalCost = sharePrice * 100



FindstockCode method returns optional value. We can access multiple optional together using Optional chaining feature.

Explain Apple push notification working

Ans : Push notifications allow developers to reach users and perform small tasks even when users aren’t actively using an app.

In iOS 10, User can do following task :

  • Display a short text message
  • Play a notification sound
  • Set a badge number on the app’s icon
  • Provide actions the user can take without opening the app
  • Show a media attachment
  • Be silent, allowing the app to wake up in the background and perform a task
Now following steps to follow to configure push notification :

1. Create app id in developer account with your app bundle id. Push notification entitlement must be enabled for this app id. (or another way for go to App Settings > Capabilities and enable push notification switch). You also have to create CSR(Certificate Signing Request) file from your keychain and assign to this app id push notification feature in developer account.

2. Now in terms of coding, first we need to ask to user for allowing user notification. After allowing, we need to register for remote notification. If all goes good, system provides you 'token' which is address of this app for this device.

3. In code, first import usernotification. Then for registering for remote notification, in didFnishLaunchingWithOptions

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge])  {
    (granted, error) in
       print("Permission granted: \(granted)")
       guard granted else { return }


 func getNotificationSettings()  {
       UNUserNotificationCenter.current().getNotificationSettings { (settings) in
       print("Notification settings: \(settings)")
       guard settings.authorizationStatus == .authorized else { return }

4. If registered for remote notification successfully, then one of the following two method will be called,

func application(_ application: UIApplication,
                 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)  {

       let tokenParts = { data -> String in
              return String(format: "%02.2hhx", data)

       let token = tokenParts.joined()
       print("Device Token: \(token)")

func application(_ application: UIApplication,
                 didFailToRegisterForRemoteNotificationsWithError error: Error)  {
  print("Failed to register: \(error)")

5. Device token is provided by APNS and this token will be converted to string. This device token shold be sent to application server or stored to database on server side.

Now lets study about payload or notification message,

Payload looks like :

  "aps": {
    "alert": "Breaking News!",
    "sound": "default",
    "link_url": ""

aps is fixed key in payload dictionary json. aps is also dictionary itself.

alert : Display text message
sound : Which sound when notification come
link_url : custom key, we can any such custom key for data
badge : number of count of badge that is displayed on app icon
category : which type of custom action notification have

Payload maximum size is 4096 kb (4 mb).

Now what when notification comes

1. If app is closed didFinishLaunchingWithOptions is called.
2. If open in background or foreground, then didReceiveRemoteNotification is called.

For 1st case,

In didFinishLaunchingWithOptions method
// Check if launched from notification

if let notification = launchOptions?[.remoteNotification] as? [String: AnyObject] {

  let aps = notification["aps"] as! [String: AnyObject]
  _ = NewsItem.makeNewsItem(aps)

  (window?.rootViewController as? UITabBarController)?.selectedIndex = 1

For 2nd case,

In didReceiveRemoteNotification,

let aps = userInfo["aps"] as! [String: AnyObject]
  _ = NewsItem.makeNewsItem(aps)

Actionable Notification

Actionable notifications let you add custom buttons to the notification. You can put reply,retweet,like button as you seen our favourite apps. This type of notification can be defined by Category.

In this type notification, we have to register category like following instead of UIApplication.shared.registerForRemoteNotifications().

func registerForPushNotifications() {
  UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
    (granted, error) in   
    print("Permission granted: \(granted)")
    guard granted else { return }
    // 1
    let viewAction = UNNotificationAction(identifier: viewActionIdentifier,
                                          title: "View",
                                          options: [.foreground])
    // 2
    let newsCategory = UNNotificationCategory(identifier: newsCategoryIdentifier,
                                              actions: [viewAction],
                                              intentIdentifiers: [],
                                              options: [])
    // 3

Above things is not enough for taking action on button. We have to add extension of UNUserNotificationCenterDelegate.

Silent Notification 

If we want to do something task without knowing to user in background, then we can send silent notification to user device. For this background modes of push notification must be checked. For push notification aps, there is key named content-available. That's value should be 1 for silent notification.

For more detail, click here.

Difference between Delegate and NSNotification

Ans :  A delegate uses protocol and creates a has-a relationship between two classes. Benefit of delegate is that we can return something back to the owning class.
Notification is like point to multi-point communication. Notification is one way  of message transmitting way.

Delegates create relationship between two classes. Notifications are used to send events to one or many classes.

We have to use delegate to specified known object. Notification for all object.

Delegate is like talking over telephone. Notification is like radio station.  

Coding of NSNotificationCenter :

[[NSNotificationCenter defaultCenter] addObjserver:self selector:@selector(useNotificationWithString:)  name:@”TimeOut” object:nil];

For BroadCast,

[[NSNotificationCenter defaultCenter] postNotificationName:@”TimeOut” object:nil userInfo:dict];

-(void) useNotificationWithString:(NSNotification *)notification
            dict = [notification userInfo];

To Remove observer,
[[NSNotificationCenter defaultCenter] removeObserver];

Difference between Objective-C Category and Extension

Ans : 

1.Category is a way to add methods to a class whether or not source code is available implies you can add category to foundation classes like NSString and also to your own custom classes.

2.We can add extra instance variable and property in class extension but not in Category.

3.Any variable and method inside the extension is not even accessible to inherited class.

4.Category and Extension both are basically made to handle large code base but category is a way to extend class API in multiple source file while extension is a way to add required methods out side the main interface file.

5.Use category when you have to break your same class code into different source file according to different functionality and Extension when you just need to add some required methods to existing class outside the main interface file. also when you need to modify a publicly declared instance variable in a class. for ex: readonly to readwrite you can re declare it in extension.

Read : What is Category?