Search Your Question

Difference between Core Data and Sqlite

Ans : Core-data is not database that we understand. Sqlite is Database. 

Lets have a look over difference between Core-data and Sqlite (or Database) :

Core Data:


  1. Primary function is graph management (although reading and writing to disk is an important supporting feature).
  2. Operates on objects stored in memory (although they can be lazily loaded from disk).
  3. Works with fully-fledged objects that self-manage a lot of their behavior and can be sub classed and customized for further behaviors.
  4. Non-transactional, single threaded, single user (unless you create an entire abstraction around Core Data which provides these things).
  5. Only operates in memory.
  6. Requires a save process.
  7. Can create millions of new objects in-memory very quickly (although saving these objects will be slow).
  8. Leaves data constraints to the business logic side of the program.


Database or SQLite:


  1. Primary function is storing and fetching data.
  2. Operates on data stored on disk (or minimally and incrementally loaded).
  3. Stores "dumb" data.
  4. Can be transactional, thread-safe, multi-user.
  5. Can drop tables and edit data without loading into memory.
  6. Perpetually saved to disk (and often crash resilient).
  7. Can be slow to create millions of new rows.
  8. Offers data constraints like "unique" keys.
Credit : http://www.cocoawithlove.com/2010/02/differences-between-core-data-and.html


difference between coredata and sqlite

Advantage of Core-data : 

  • Much better memory management. With a plist you must load the entire thing into memory; with Core Data only the objects you're currently using need to be loaded. Also, once objects are loaded, they're normally placeholder "fault" objects whose property data doesn't load until you need it.
  • Related to the above, when you have changes, you can save only the changed objects, not the entire data set.
  • You can read/write your model objects directly instead of converting them to/from something like an Dictionary.
  • Built-in sorting of objects when you fetch them from the data store.
  • Rich system of predicates for searching your data set for objects of interest.
  • Relationships between entities are handled directly, as properties on the related objects. With a plist you would need to do something like store an object ID for a relationship, and then look up the related object.
  • Optional automatic validation of property values.
More about Core-data : 

  • CoreData isn't a Database. It's an object persistence layer. There is no concept of primary keys or foreign keys in CoreData.
  • If you want to establish a relationship between two entities. You'll define a relationship, CoreData takes care of how that relationship is stored.
  • Select an entity, use plus button at the bottom of the entities attributes list, select add relationship, select the destination entity from the dropdown.
  • Select the destination entity and define an inverse relationship in the same way.

What is lazy property?

Ans : 

When to use lazy initialization is when the initial value for a property is not known until after the object is initialized.

For example, if you have a Person class and a personalizedGreeting property. The personalizedGreeting property can be lazily instantiated after the object is created so it can contain the name of the person.

class Person {      
  var name: String
    
  lazy var personalizedGreeting: String = {
    return "Hello, \(self.name)!"
  }()
    
  init(name: String) {
    self.name = name
  }
}

When you initialize a person, their personal greeting hasn’t been created yet:

let person = Person(name: "John Doe") // person.personalizedGreeting is nil But when you attempt to print out the personalized greeting, it’s calculated on-the-fly:

NSLog(person.personalizedGreeting)

Bonus Tip : You do need to declare your lazy property using the var keyword, not the let keyword, because constants must always have a value before initialization completes.

Benefit of lazy property increase performance in terms of speed.

Explain defer keyword or defer statement in Swift

Ans : Defer block is executed just before return statement or exit of block. Let's have a look to following chunk of code for better understanding

      func defer()  { 
          print("Start") 
          var value: String? 
         defer { 
              if let v = value { 
                   print("Ending execution of \(v)")
              } 
        } 
      value = "defer function" 
      print("End") 
   }

So printing sequence is like following :

Start
End
Ending execution of defer function

So in short defer block will be called lastly in the current block. It will be executed in any case like before return, before the break, before throw exception. Yes, if exception comes, then also defer block will be called before program crash or going to exception.

If there is multiple defer block in same method, Then defer block will execute from down to up side.


Write a program to find missing number of array of 1 to n.

Ans : 


      import Foundation
        
        let arr = [1,2,4,5,8,6,9,7]
        let n = arr.count
        let total = ((n + 1)*(n + 2))/2
        var missingNum = total
        for item in arr {
            missingNum = missingNum - item
        }
        print(missingNum)

Write a program to distinguish lowercase and uppercase character from String in swift

Ans : 

Method 1 : 

let string = "iOSiQA is Very Helpful WebSite to Prepare for iOS Interview."
var output = ""

for chr in string {
    var str = String(chr)
    if str.lowercaseString != str {
        output += str
    }
}
print(output)


>>> OSQAVHWPOSI

Method 2 : 

let testString = "iOSiQA is Very Helpful WebSite to Prepare for iOS Interview."
let lowerCase = NSCharacterSet.lowercaseLetterCharacterSet()
let upperCase = NSCharacterSet.uppercaseLetterCharacterSet()

for currentCharacter in testString.utf16 {
  if lowerCase.characterIsMember(currentCharacter) {
    println("Character code \(currentCharacter) is lowercase.")
  } else if upperCase.characterIsMember(currentCharacter) {
    println("Character code \(currentCharacter) is UPPERCASE.")
  } else {
    println("Character code \(currentCharacter) is neither upper- nor lowercase.")
  }

}



Method 3 : 

let testString = "Åke röstet un café in Владивосток!"
let lowerCase = CharacterSet.lowercaseLetters
let upperCase = CharacterSet.uppercaseLetters

for currentCharacter in testString.unicodeScalars {
    if lowerCase.contains(currentCharacter) {
        print("Character code \(currentCharacter) is lowercase.")
    } else if upperCase.contains(currentCharacter) {
        print("Character code \(currentCharacter) is UPPERCASE.")
    } else {
        print("Character code \(currentCharacter) is neither upper- nor lowercase.")
    }
}

Method 4 :   to identify character is uppercase or lowercase

extension Character {

        func isUpperCase() -> Bool {
            return CharacterSet.uppercaseLetters.contains(self.unicodeScalars.first!)
        }

        func isLowerCase() -> Bool {
            return CharacterSet.lowercaseLetters.contains(self.unicodeScalars.first!)
        }


  }

Write a program to reverse string in swift

Ans : 

Using Self made function : 

func reverse(_ s: String) -> String {
       var str = ""
       //.String is just like array of characters

       for character in s.characters {
            str = "\(character)" + str
            print ( str)
       }
   return str
}

print (reverse("!pleH"))


Using Swift Direct method : 

Swift 4.0

let str = "abc"

String(str.reversed())

or 

String(str.characters.reversed())



Difference between mutable array and immutable array?

Ans : 

Mutable Array content can be changed but Immutable Array content can not be changed.

You can insert, update, remove item from Mutable Array, but same is not possible in Immutable Array. There is no any methods like RemoveItem or ReplaceItem for Immutable Array, which are available for Mutable Array.

So in Immutable Array, content can not be changed after initialisation. It is either be initialised by content or by nil.

Use of Immutable array 

1. Used when we want to give array to other coder who can't be change array content.
2. Used when only fixed contents are there like array of months, days which can't be changed.

CollectionViewDelegate and CollectionViewDataSource Methods

Ans :
Popular methods is designed by blue color.

CollectionViewDelegate Methods

Managing the Selected Cells
func collectionView(UICollectionView, shouldSelectItemAt: IndexPath) -> Bool
Asks the delegate if the specified item should be selected.

func collectionView(UICollectionView, didSelectItemAt: IndexPath)
Tells the delegate that the item at the specified index path was selected.

func collectionView(UICollectionView, shouldDeselectItemAt: IndexPath) -> Bool
Asks the delegate if the specified item should be deselected.

func collectionView(UICollectionView, didDeselectItemAt: IndexPath)
Tells the delegate that the item at the specified path was deselected.

Managing Cell Highlighting
func collectionView(UICollectionView, shouldHighlightItemAt: IndexPath) -> Bool
Asks the delegate if the item should be highlighted during tracking.

func collectionView(UICollectionView, didHighlightItemAt: IndexPath)
Tells the delegate that the item at the specified index path was highlighted.

func collectionView(UICollectionView, didUnhighlightItemAt: IndexPath)
Tells the delegate that the highlight was removed from the item at the specified index path.

Tracking the Addition and Removal of Views
func collectionView(UICollectionView, willDisplay: UICollectionViewCell, forItemAt: IndexPath)
Tells the delegate that the specified cell is about to be displayed in the collection view.

func collectionView(UICollectionView, willDisplaySupplementaryView: UICollectionReusableView, forElementKind: String, at: IndexPath)
Tells the delegate that the specified supplementary view is about to be displayed in the collection view.

func collectionView(UICollectionView, didEndDisplaying: UICollectionViewCell, forItemAt: IndexPath)
Tells the delegate that the specified cell was removed from the collection view.

func collectionView(UICollectionView, didEndDisplayingSupplementaryView: UICollectionReusableView, forElementOfKind: String, at: IndexPath)
Tells the delegate that the specified supplementary view was removed from the collection view.


Handling Layout Changes
func collectionView(UICollectionView, transitionLayoutForOldLayout: UICollectionViewLayout, newLayout: UICollectionViewLayout) -> UICollectionViewTransitionLayout
Asks for the custom transition layout to use when moving between the specified layouts.

func collectionView(UICollectionView, targetContentOffsetForProposedContentOffset: CGPoint) -> CGPoint
Gives the delegate an opportunity to customize the content offset for layout changes and animated updates.

func collectionView(UICollectionView, targetIndexPathForMoveFromItemAt: IndexPath, toProposedIndexPath: IndexPath) -> IndexPath
Asks the delegate for the index path to use when moving an item.

Managing Actions for Cells
func collectionView(UICollectionView, shouldShowMenuForItemAt: IndexPath) -> Bool
Asks the delegate if an action menu should be displayed for the specified item.

func collectionView(UICollectionView, canPerformAction: Selector, forItemAt: IndexPath, withSender: Any?) -> Bool
Asks the delegate if it can perform the specified action on an item in the collection view.

func collectionView(UICollectionView, performAction: Selector, forItemAt: IndexPath, withSender: Any?)
Tells the delegate to perform the specified action on an item in the collection view.

Managing Focus in a Collection View
func collectionView(UICollectionView, canFocusItemAt: IndexPath) -> Bool
Asks the delegate whether the item at the specified index path can be focused.

func indexPathForPreferredFocusedView(in: UICollectionView) -> IndexPath?
Asks the delegate for the index path of the cell that should be focused.

func collectionView(UICollectionView, shouldUpdateFocusIn: UICollectionViewFocusUpdateContext) -> Bool
Asks the delegate whether a change in focus should occur.

func collectionView(UICollectionView, didUpdateFocusIn: UICollectionViewFocusUpdateContext, with: UIFocusAnimationCoordinator)
Tells the delegate that a focus update occurred.

Controlling the Spring-Loading Behavior
func collectionView(UICollectionView, shouldSpringLoadItemAt: IndexPath, with: UISpringLoadedInteractionContext) -> Bool
Returns a Boolean value indicating whether you want the spring-loading interaction effect displayed for the specified item.


UICollectionViewDataSource Methods


Getting Item and Section Metrics
func collectionView(UICollectionView, numberOfItemsInSection: Int) -> Int  (Required)
Asks your data source object for the number of items in the specified section.

func numberOfSections(in: UICollectionView) -> Int
Asks your data source object for the number of sections in the collection view.

Getting Views for Items
func collectionView(UICollectionView, cellForItemAt: IndexPath) -> UICollectionViewCell  (Required)
Asks your data source object for the cell that corresponds to the specified item in the collection view.

func collectionView(UICollectionView, viewForSupplementaryElementOfKind: String, at: IndexPath) -> UICollectionReusableView
Asks your data source object to provide a supplementary view to display in the collection view.

Reordering Items
func collectionView(UICollectionView, canMoveItemAt: IndexPath) -> Bool
Asks your data source object whether the specified item can be moved to another location in the collection view.

func collectionView(UICollectionView, moveItemAt: IndexPath, to: IndexPath)
Tells your data source object to move the specified item to its new location.

Configuring an Index
func indexTitles(for: UICollectionView) -> [String]?
Asks the data source to return the titles for the index items to display for the collection view.

func collectionView(UICollectionView, indexPathForIndexTitle: String, at: Int) -> IndexPath
Asks the data source to return the index path of a collection view item that corresponds to one of your index entries.

Write program for ascending sorting Int Array in any language

Ans : 
(Interviewer told syntax doesn't matter, write pseudo-code type program)

1. Not using direct function.

 void main()
    {

        int i, j, a, n, number[30];
        printf("Enter the value of N \n");
        scanf("%d", &n);

        printf("Enter the numbers \n");
        for (i = 0; i < n; ++i)
            scanf("%d", &number[i]);

        for (i = 0; i < n; ++i)
        {

            for (j = i + 1; j < n; ++j)
            {

                if (number[i] > number[j])
                {

                    a =  number[i];
                    number[i] = number[j];
                    number[j] = a;

                }

            }

        }

        printf("The numbers arranged in ascending order are given below \n");
        for (i = 0; i < n; ++i)
            printf("%d\n", number[i]);

    }

2. If we write in swift using higher order function, then

var numbers = [45,6,113,56,8,56,43,78]

print(numbers.sort()) //Sorting in Ascending order

print(numbers.sort(>)) //Sorting in Descending order

Interviewer mostly asked this question to check your programming logic. So he/she don't require syntax.

Q. Sorting strings array
A.
Method 1 : 
var sortedArray = swiftArray.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }

Method 2 : 
let sortedNames = names.sort { $0.name < $1.name }
let sortedNames = names.sorted(by: <)


Difference between Swift Array and Objective C Array

Ans : Swift arrays (Array and for short, []) are passed by value which means
that every object contained will be copied.

NSArray are implemented as classes (and bridged from ObjC) so they're passed as references.

In Swift, we can declare three type of array.
One is Array or [],
Second is NSArray,
Third is NSMutableArray.

NSArray and NSMutableArray are coming from Objective C by bridge. So interviewer may ask what are difference between types arrays in swift?

Extract value from Array : 

Get 3rd Value from Array

Objective C : [arr objectAtIndex:2] // 2 due to index start from 0 in array

Swift : arr[2]