Lecture 5 Objective-C Compatibility

Objective-C Compatibility


  • Virtually all of the iOS API is accessible seamlessly from Swift.
  • A few special data types are handled specially and powerfully via bridging.
  • Bridging means that you can use them interchangeably.
  • NSString is bridged to String.
  • NSArray is bridged to Array<AnyObject>.
  • NSDictionary is bridged to Dictionary<NSObject, AnyObject>.
  • Int, Float, Double, Bool are all bridged to NSNumber (but not vice-versa).
  • To get from NSNumber to these types use doubleValue, intValue, etc.
  • Int, Float, Double are bridged to the C types int, float, double.

Continue Reading…

Lecture 4 More Swift and Foundation Frameworks

Optional and enum

An optional is just an enum

Continue Reading…

Lecture 12 Core Data

Core Data

How to get a NSManagedObjectContext

Create a UIManagedDocument and ask for its managedObjectContext.

Creating a UIManagedDocument

This only creates the UIManagedDocument instance, but does not open nor create the underlying file.

Open or create a UIManagedDocument

  1. First, check to see if the UIManagedDocument‘s underlying file exits on disk …

  2. … if it does, open the document using …

  3. … if it does not, create the document using …

  4. Completion handlers are needed because open/save is asynchronous !

Once document is open/created, start using it

Check the documentState when use it …

Other documentStates

  • UIDocumentStateClosed
  • UIDocumentStateSavingError
  • UIDocumentStateEditingDisabled
  • UIDocumentStateInConflict

Use document

Saving the document

  • UIManagedDocuments autosave themselves!
  • Save manually

  • This a UIKit class and so this method must be called on the main queue.

Closing the document

  • Will automatically close if there are no strong pointers left to it.
  • Close manually (asynchronous!) …

Inserting objects into the database

  • This NSEntityDescription class method returns an NSManagedObject instance.
  • All objects in the database are represented by NSManagedObject or subclasses thereof.
  • An instance of NSManagedObject is a manifestation of an Entity in our Core Data Model.
  • Attributes of a newly-inserted object will start out nil.



Four important things involved in creating an NSFetchRequest

  1. Entity
  2. How many objects to fetch at a time and/or maximum to fetch
  3. NSSortDescriptors to specify the order in which the array of fetched objects are returned
  4. NSPredicate specifying which of those Entities to fetch

Creating an NSFetchRequest


Executing the fetch

  • Returns nil if there is an error (check the NSError for details)
  • Returns an empty array if there are no matches in the database.
  • Returns an NSArray of NSManagedObjects if there were any matches.


Watch a document’s managedObjectContext


Merging changes