Search Your Question

Showing posts with label Airit Media LLP. Show all posts
Showing posts with label Airit Media LLP. Show all posts

What is multiplier and ratio in auto layout in ios?

Ans :


Difference between Multiplier and Ratio : 

There is not any difference. Both are using for same purpose.

The Aspect Ratio is really just a convenient way to express the Multiplier when working in Interface Builder. It effectively gets "converted" to a multiplier.

You can confirm this while debugging by inspecting the constraint's .multiplier property. If you set a view's width to 60, and multiplier to 1:2 (resulting in an auto-layout height of 120), the actual value of .multiplier will be 0.5.

So, in my view, it depends on what feels more natural.

If I want a view to be 90% of the width of another view, I am much more likely to set the Multiplier to 0.9 --- which gives the exact same result as setting it to 9:10.

However, if I want a view to maintain an aspect ration of, say, 3-to-2, I am much more likely to set the Multiplier to 3:2 rather than 1.5.

Using a ratio can also be convenient when you have "non-simple" values. That is, it's easy to understand that a ratio of 3:2 is the same as 1.5. But what if I have an image with native size of 281 x 60, and I want to use those values to maintain ratio? 281:60 is easier to understand than .multiplier = 4.68333339691162.

And, while they are interchangeable, it is probably a bit more intuitive to use Ratio when constraining an object to itself - e.g. I want my view's width to be 2 x its own height, so 2:1 - and using Multiplier when constraining one object to another - e.g. I want my view's width to be 75% of the width of its superview, so 0.75.

Why array method containObject has id as parameter in ios?

Ans : id is a generic type. This means that the compiler will expect any object type there, and will not enforce restrictions. It can be useful if you're expecting to use more than one class of objects there. So you can add anything of type id to an NSArray.

So array method containObject has id type as parameter.

- (BOOL)containsObject:(ObjectType)anObject;

Usage :

bool bVal = [arr containObject:@5];

What are join in sql? Explain Types of Join

Ans :

Join :
When we need data from more than 1 table, then we can fetch data from those table using joining those table. It will return only matching data from two tables.

Select * from table1 t1 inner join table2 t2 on t1.column1 = t2.column1

Types of Join :

1. Inner Join :
If we use inner join between two table, then only data exists in both table, are returned.

2. Outer Join :
    Left Outer Join : It returns all data from left table(table1) and only matching data from both table.
    Right Outer Join : It returns all data from right table(table2) and only matching data from both table.

3. Cross Join : It is like cartesian join. It returns all records from both table and it returns table1.count * table2.count records in returns. Suppose table1 has 4 records and table2 has 3 records and returns 4*3 records.

4. Self Join : If some column's reference has in same table then self join is used. It is same like inner join but here both left and right table are same. Its like if you table and Columns are such as MainID, Name, ParentID then you can make query like
Select * from table t1 join table t2 on t1.MainID = t2.ParentID

Difference between Strong and Weak in iOS

Ans : 


Strong
strong property means that you want to “own” the object. Only when you set the property to nil will the object be  destroyed. Unless one or more objects also have a strong reference to the object. This is the one you will use in most cases.
  1. Creates ownership between property and assigned value.
  1. This is default for object property in ARC so it does not let you worrying about reference count and release the reference automatically.
  1. It is replacement for retain. We use if and only if we need to use as retain.
  1. Retain count will be incremented.
  1. Creates non-ownerships between property and assigned value.
  1. Strong is used on parent object and weak is used on child object when parent is released then child object reference is also set to nil
  1. It helps to prevents retain cycles.
  1. It doesn’t protect the referenced object when collection by garbage collector.
  1. Weak is essentially assigned, un-retain property.
  1. Retain count will not be incremented.


Weak
Weak property means you don’t want to have control over the objects lifecycle. The object only lives on while another objects has a strong reference to it. If there are no strong references to the object then it will be destroyed. 
Weak reference is useful to avoid situation like retain cycle. Retain cycle occurs when two or more objects have strong reference to each other. This two object will never be freed in memory due to strong reference. So to avoid weak reference, One object has a strong ownership reference to another object, and another object should be have a weak reference to first object.

Strong references should be used when a parent object is referencing a child object and never the other way around. That is, a child class should not have a strong reference to the parent class.

Weak references should be used to avoid retain cycles and an object has the possibility to become nil at any point of it’s lifetime.

Good read : Click here




Explain MVC through implementation of UITableView

Ans :

Read first about MVC

Let's understand to implement UITableview in MVC

1. We write fetching data query or request web-service and parse json,xml and save data to any global variable like dictionary, array, etc. So all inserting, fetching methods and data variable are comes under M.....Model

2. We make custom tableview cell, and put various types of views like UILabel, UITextField, UIButton for displaying in UITableView on screen. So this comes under V....View.

3. For displaying TableView, we will take UIVIewController or UITableviewController. This are responsible for various activity like telling how many section, rows are there, on delete button deleting row, how much height of cell, etc... So this comes under C....Controller.

Which delegate method called when I click on push notifications?

Ans : 
Different app delegate method called depends on following scenarios

For silent notification : 

App is in Foreground
No system alert shown
application:didReceiveRemoteNotification:fetchCompletionHandler: is called

App is in Background
System alert is shown
application:didReceiveRemoteNotification:fetchCompletionHandler: is called

App is in Suspended
App state changes to Background
System alert is shown
application:didReceiveRemoteNotification:fetchCompletionHandler: is called

App is Not Running because killed by user
System alert is shown
No callback is called

Normal Push Notification (no content-available) :

App is in Foreground
No system alert shown
application:didReceiveRemoteNotification:fetchCompletionHandler: is called

App is in Background or Suspended
System alert is shown
No method is called, but when user tap on the push and the app is opened
application:didReceiveRemoteNotification:fetchCompletionHandler: is called

App is in Not Running
System alert is shown
No method is called, but when user tap on the push and the app is opened
application:didFinishLaunchingWithOptions: then application:didReceiveRemoteNotification:fetchCompletionHandler: are both called

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.

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:

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)

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:



How to take common elements from two array in ios?

Ans. 

Swift higher order function is very useful. See below example.


let fruitsArray = ["apple", "mango", "blueberry", "orange"]
let vegArray = ["tomato", "potato", "mango", "blueberry"]

// only Swift 1
let output = fruitsArray.filter{ contains(vegArray, $0) }

// in Swift 2 and above
let output = fruitsArray.filter{ vegArray.contains($0) }
// or
let output = fruitsArray.filter(vegArray.contains)


Array vs Set

let array1: Array = ...
let array2: Array = ...

// Array
let commonElements = array1.filter(array2.contains)

// vs Set
let commonElements = Array(Set(array1).intersection(Set(array2)))

// or (performance wise equivalent)

let commonElements: Array = Set(array1).filter(Set(array2).contains)

Another way in Swift 4.0

   var someHash: [String: Bool] = [:]

   fruitsArray.forEach { someHash[$0] = true }

   var commonItems = [String]()

   vegArray.forEach { veg in
    if someHash[veg] ?? false {
        commonItems.append(veg)
    }
   }


   print(commonItems)



What is category?

Ans : It is used to extend the functionality of the class. Implementation of category is in different file with name like classname + categoryname.h and .m file.

Read : Differnce between Category and Extension


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 frames and bounds.

Ans : 

Frame :  View's location and size using the parent view's coordinate system
Needed while placing the view in the parent

bounds = View's location and size using its own coordinate system
Needed while placing the view's content or subviews within itself

The bounds of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to its own coordinate system (0,0).

The frame of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to the superview it is contained within.

So, imagine a view that has a size of  50x50 (width x height) positioned at 15,15 (x,y) of its superview. The following code prints out this view's bounds and frame:

NSLog(@"bounds.origin.x: %f", label.bounds.origin.x);
NSLog(@"bounds.origin.y: %f", label.bounds.origin.y);
NSLog(@"bounds.size.width: %f", label.bounds.size.width);
NSLog(@"bounds.size.height: %f", label.bounds.size.height);

NSLog(@"frame.origin.x: %f", label.frame.origin.x);
NSLog(@"frame.origin.y: %f", label.frame.origin.y);
NSLog(@"frame.size.width: %f", label.frame.size.width);
NSLog(@"frame.size.height: %f", label.frame.size.height);

Output : 

bounds.origin.x: 0
bounds.origin.y: 0
bounds.size.width: 50
bounds.size.height: 50

frame.origin.x: 15
frame.origin.y: 15
frame.size.width: 50
frame.size.height: 50

So, we can see that in both cases, the width and the height of the view is the same regardless of whether we are looking at the bounds or frame. What is different is the x,y positioning of the view. In the case of the bounds, the x and y coordinates are at 0,0 as these coordinates are relative to the view itself. However, the frame x and y coordinates are relative to the position of the view within the parent view (which earlier we said was at 25,25).

For more understanding : Visit this