Search Your Question

Delete record from Core-data

Ans: 

Deleting a record from a persistent store involves three steps:

  1. Fetch the record that needs to be deleted
  2. Mark the record for deletion
  3. Save the changes
Code : 


let fetchRequest: NSFetchRequest<Profile> = Profile.fetchRequest()
fetchRequest.predicate = Predicate.init(format: "profileID==\(withID)")
let objects = try! context.fetch(fetchRequest) // Step 1
for obj in objects {
    context.delete(obj)  // Step 2
}

do {
    try context.save() //  <- remember to save data // Step 3
} catch {
    // Do something... 
}

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)