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

[iOS 7 Stanford 2013 Fall]Lecture 13 Core Data and Table View

Core Data and UITableView


  • Simply hooks an NSFetchedRequest up to a UITableViewController
  • Usually have an NSFetchedResultsController @property in UITableViewController
  • Use NSFetchedResultsController to answer all UITableViewDataSource protocol’s questions!

Sample Code

Very important method … objectAtIndexPath:

NSFetchedResultsController method…

Create a NSFetchedResultsController

  • Be sure that any cacheName is always associated with exactly the same request.
  • It is critical that the sortDescriptor matches up with the keyPath

NSFetchedResultsController Delegate

NSFRC also watches changes in Core Data and auto-updates table

[iOS 7 Stanford 2013 Fall] Lecture 5 View Controller Lifecycle

Lecture 5 View Controller Lifecycle



UITextView: Like UILabel, but multi-line, selectable/editable, scrollable, etc

How to set text view’s NSMutableAttributedString?

  • Obtain the NSMutableAttributedString representing the text in the UITextView using

  • NSTextStorage is a subclass of NSMutableAttributedString

Setting the font

  • Set font: @property (nonatomic, strong) UIFont *font;

Advanced layout in UITextView with TextKit

  • This property defines “where text can be” in the UITextView

  • This object will read characters from textStorage and lays down glyphs into textContainer

View Controller Lifecycle


  • After instantiation and outlet-setting, viewDidLoad is called.
  • This an exceptionally good place to put a lot of setup code.
  • However, geometry of view (its bounds) is not set yet!
  • At this point, you can’t be sure you’re on an iPhone 5-sized screen or an iPad or ???. (WTF?)
  • Do not initialize things that are geometry-dependent here.


  • View will only get “loaded” once, but it might appear and disappear a lot.
  • Do something here if things you display are changing while your MVC is off-screen.
  • View’s geometry is set here, but there are other (better) places to react to geometry.


Geometry changed?

  • Most of the time this will be automatically handled with Autolayout.

  • Called any time a view’s frame changed and its subviews were thus re-layed out.

  • Set the frames of subviews here or set other geometry-affecting properties.

  • Between “will” and “did”, autolayout will happen.


  • The view controller returns YES from shouldAutorotate
  • The view controller returns the new orientation in supportedInterfaceOrientations
  • The application allows rotation to that orientation (defined in Info.plist file).


  • In low-memory, this method is called.
  • Anything “big”, such as images and sounds that can be recreated should probably be released.


  • This method is sent to all objects that come out of a storyboard (including Controllers).
  • Happens before outlets are set!
  • Anything that would go in your Controller’s init method would have to go in awakeFromNib too, because init methods are not called on objects that come from a storyboard.

    • (void)setup { };
    • (void)awakeFromNib { [self setup]; }
    • (instancetype)initWithNibName:(NSString *)name bundle:(NSBundle *)bundle { self = [super initWithNibName:name bundle:bundle]; [self setup]; return self; }




The “radio station”


Get the default “notification center” via [NSNotificationCenter defaultCenter]

Receive the notification

Tune out when done listening

  • A good place to do so is viewWillDisappear:
  • Or in a method called dealloc

[iOS 7 Stanford 2013 Fall] Lecture 4 Foundation and Attributed String

More Objective-C

Creating Objects

1. alloc and int

2. Class Methods

3. Sometimes Both a Class Method and init Method Exist

4. Other Objects Creates New Objects


  • Sending messages to nil is (mostly) okay. No code executed.
  • Be careful if the method returns a C struct. Return value is undefined.


  • id means pointer to an object of unknown/unspecified type.
  • Really all object pointers are treated like id at run time.
  • Figuring out the code to execute when a message is sent at runtime is called “dynamic binding“.
  • Program crashs when someone is sending messages to an object that it doesn’t understand.
  • In order to be safe, we mostly use static type (e.g. NSString *, point out the type explicitly) and the compiler is really smart.
  • Compiler will not complain about assignment between an id and a statically typed variable.
  • Never use id *, because id is alreay a pointer.


  • Asking at runtime what class an object is or what messages can be sent to it.
  • isKindOfClass: inheritance included
  • inMemberOfClass: no inheritance
  • respondsToSelector: returns whether an object responds to a given method


SEL is the Objective-C “type” for a selector




  • Immutable
  • All objects in the array are held onto strongly
  • Shortcut to create: *@[]


  • Mutable version of NSArray
  • for-in


New syntax for creating an NSNumber in iOS 6: @()


  • I don’t know too much about this class.
  • Generic object wrapper for some non-object, non-primitive data types (i.e. C structs, interesting)


  • Bag of bits.
  • Used to save/restore/transmit raw data throughout the iOS SDK.


  • Used to find out the time right now or to store past or future times/dates.


  • No ordering.
  • Unique object



  • Immutable collection of objects looked up by a key (simple hash table).
  • All keys and values are held onto strongly by an NSDictionary.


  • Mutable version of NSDictionary.

Property Lists and NSUserDefault

  • It means any graph of objects containing only: NSArray, NSDictionary, NSNumber, NSString, NSDate, NSData.
  • SDK usually read property lists from somewhere or write them out to somewhere.

  • NSUserDefault: lightweight storage of property lists.


  • C struct (not a class)
  • Important location value NSNotFound.

UIFont and UIColor

  • Fonts in iOS 7 are very important to get right.
  • It is best to get a UIFond by asking for the preferred font for a given text style.

  • UIFontDescriptor: attempts to categorize a font anyway.


  • A NSString where each character has an NSDictionary of “attributes”.

Attributed String in UITextView and UILabel

[iOS 7 Stanford 2013 Fall] Lecture 2 Xcode


Lazy Initialization


Getter & Setter

If implements both setter and getter, @synthesize is required.

Utility Method

A (usually) static method. Used when you need to do stuff that does not need an instance of a class.


  • instancetype basically tells the compiler that this method returns an object which will be the same type as the object that this message was sent to.
  • Almost only for init.