Search Your Question

Add column in SQLite

Ans : 
If we have uploaded our app ver 1.0 and we want to add columns in sqlite database, then following thing can done.

If we have sqlite database which table structure can be changed after release. Then we need to maintain database version. We can update database version by excecuting query like PRAGMA user_version = version_num; (For swift : PRAGMA table_info(tblTest))

In second release If we need to add columns, then we can check database version, If database version is old version then we can execute following query :

ALTER TABLE {tableName} ADD COLUMN COLNew {type};

Query for last inserted row in SQL database

Ans. 

If column is primary key and integer, then ,

Sqlite : SELECT * FROM table ORDER BY column DESC LIMIT 1;

or

SELECT * FROM table WHERE ID = SELECT LAST_INSERT_ROWID()

FMDB : 

Last inserted id is : [fmdb lastInsertRowId];

Sqlite3 all functions : 

sqlite3_open: This function is used to create and open a database file. It accepts two parameters, where the first one is the database file name, and the second a handler to the database. If the file does not exist, then it creates it first and then it opens it, otherwise it just opens it.
sqlite3_prepare_v2: The purpose of this function is to get a SQL statement (a query) in string format, and convert it to an executable format recognisable by SQLite3.
sqlite3_step: This function actually executes a SQL statement (query) prepared with the previous function. It can be called just once for executable queries (insert, update, delete), or multiple times when retrieving data. It’s important to have in mind that it can’t be called prior to the sqlite3_preprare_v2 function.
sqlite3_column_count: This method’s name it makes it easy to understand what is about. It returns the total number of columns (fields) a contained in a table.
sqlite3_column_text: This method returns the contents of a column in text format, actually a C string (char *) value. It accepts two parameters: The first one is the query converted (compiled) to a SQLite statement, and the second one is the index of the column.
sqlite3_column_name: It returns the name of a column, and its parameters are the same to the previous function’s.
sqlite3_changes: It actually returns the number of the affected rows, after the execution of a query.
sqlite3_last_insert_rowid: It returns the last inserted row’s ID.
sqlite3_errmsg: It returns the description of a SQLite error.
sqlite3_finalize: It deletes a prepared statement from memory.

sqlite3_close: It closes an open database connection. It should be called after having finished any data exchange with the database, as it releases any reserved system resources.

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:

Sorting

- 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

Difference between the atomic and nonatomic attributes?

Ans : 

Atomic property give guarantee that valid value will be return. But valid does not mean that correct value.

This also not mean that atomic property are thread safe. Different threads can attempt to read and write value at same time. So one of two value will be return - value before change or changed value.

So atomic property is suffering from performance hit due to locking and unlocking before and after get or set value.

Non atomic property has no guarantee regarding correct value, a partially correct value or may be garbage value.
This is not thread safe this enhanced speed of access property.

Atomic property lock while setting value,

While non atomic property does not lock while setting value. 

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:

Inheritance
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.

i.e 

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) {
        self.name = name
    }
}

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

println(aClass.name) // "Sue"
println(bClass.name) // "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) {
        self.name = name
    }
}

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

println(aStruct.name) // "Bob"
println(bStruct.name) // "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)

Latest version of iOS, Swift, XCode

Ans : 
As per today (18-Oct-2018),

Latest version of

XCode : 10.0
Swift : 4.2
iOS : 12.0
Mac OS : mojave 10.14
Objective C : 2.0

I am using XCode 9.3, Swift 3.0, iOS 11 and mac os as High sierra.

Swift Version History :

DateVersion
2014-09-09Swift 1.0
2014-10-22Swift 1.1
2015-04-08Swift 1.2
2015-09-21Swift 2.0
2016-09-13Swift 3.0
2017-09-19Swift 4.0
2018-03-29Swift 4.1
2018-09-17Swift 4.2



What is @escaping and @nonescaping in swfit?

Ans : 

Closure : Closure are self contained blocks of functionality that can be passed around and used in code.


In swift 1.x and 2.x, closure parameter is @escaping by default. It means closure can be escape during function body execution. If don't want to escape, we have to mention @nonescaping as parameter.

In swift 3.x and after, closure parameter is @nonescaping by default.
Life cycle of non-escaping closure
Basically, a non-escape closure can only run the contents inside of it’s body, anything outside of it’s closure cannot be used. A non-escape closure tells the complier that the closure you pass in will be executed within the body of that function and nowhere else. When the function ends, the closure will no longer exist in memory. For example, if we needed to extract any values within our closure to be used outside of it, we may not do so. During the earlier days of Swift, closure parameters were escaping by default. Due to better memory management and optimizations, Swift has changed all closures to be non-escaping by default.

var closuresArray: [() -> Void] = []
func doClosures(completion: () -> Void){
completionHandlers.append(completion)
}
//ERROR!!!
passing non-escaping parameter 'completion' to function expecting an @escaping closure

Here is an example of an non-escaping closure. Here we have an empty array of closure and a function that includes a closure. If we were to append the closure in the function to the array of closure, we cannot do so because it is defaulted to non-escape. One great thing about Xcode is that it will that you that you need an escaping closure and can implement it for you.
Escaping Closure : 
Essentially escaping closure is the opposite of non-escaping closure. An escaping closure grants the ability of the closure to outlive the function and can be stored elsewhere. By using escape closure, the closure will have existence in memory until all of it’s content have been executed. To implement escaping closure, all we have to do is put @escaping in front of our closure. If you are unsure whether your closure needs escaping, no worries, as I’ve said before the complier is smart enough to let you know.
There are several ways when we need to implement an escaping closure. One instance is when we use asynchronous execution. When we are dealing with dispatch queue, the queue will hold onto the closure for you, and when the queue is done completing its work, then it will return back to the closure and complete it. Since dispatch queue is outside of the scope, we need to use escaping closure. Another instance is when we need to store our closure to a global variable, property, or any bit of storage that lives on past the function.

Always remember to use weak self while using a closure.

Difference between Stack and Heap

Ans. 

1. Stack is used for static memory allocation, Heap is used for dynamic memory allocation.

2. Variables allocated on the stack are stored directly into memory and access memory very faster and its allocation dealt with compile time.
  Variable allocated on the heap have their memory allocated at run time and accessing their memory is bit slower.

3. Stack is always reserved in LIFO order, but you can allocate and release any element/block on heap anytime. So this is much complex to say about which block is free or allocated at given time.

4. You can use stack when you know how much data you need to allocate before compile time and they are not too big. You can use heap when you don't know how much data you need to allocate or they are too big.

5. Stack is thread specific and heap is application specific. In multi threaded, each thread has its own stack.

Stack allocation vs Heap allocation (Why stack is faster than heap)

Stack allocation means that assembly just needs to increment stack pointer and that’s it. How ever in case of heap, there is lot more going on. The memory allocator needs to ask kernel for some free page, needs to partition the page properly, with time fragmentation may occur, etc. Thus with one word to say, lot of work. Struct is stored in stack and class is stored in heap.

Which delegate method called when I click on app icon, while app is in background?

Ans :

Following methods called :

If not background : 

1. DidFInishLaunchingWithOptions

If background : 

1. application Willenterforeground
2. applicationDidBecomeActive

Tricky note : Here didFinishLaunchingWithOptions not called.

Q. Which app delegate methid called when application is to be killed?
A. applicationWillTerminate: