iOS General Flashcards

(166 cards)

1
Q

What states can a running UIApplication be in?

A

UIApplicationState: Active, Inactive, and Background

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What classes would you use to encode and decode NSCoding compliant classes into a format that can be stored in a file?

A

NSKeyedArchiver and NSKeyedUnarchiver

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the C-based API for concurrent programming?

A

Grand Central Dispatch

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the object oriented API for concurrent programming?

A

NSOperation (and NSOperationQueue)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How many view controllers does a UISplitViewController manage?

A

Either one (if it is collapsed) or two

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the main limitation when using Objective C categories?

A

A category cannot define new instance variables or add new storage to a class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Name a common cause of exc_bad_access

A

Trying to access an object that has been released (or not initialized)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Name a common way of tracking down the cause of exc_bad_access

A

Enable zombie objects within the Xcode scheme

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What do you need to do in a project to use Swift from Objective C?

A

Xcode creates a ‘generated header’ automatically, you just need to import it

(But note that classes need to extend NSObject or be marked with the @objc attribute in order to be available to Objective C - and of course don’t expose things like tuples, that only exist for Swift)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What do you need to do in a project to use Objective C from Swift?

A

Create a ‘bridging header’ that imports the required code

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Does a delegating object maintain a strong or weak reference to its delegate?

A

Weak

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the Swift equivalent of Objective C categories?

A

Extensions

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is a workaround for categories not being able to add new instance variables to a class?

A

Use ‘Associated Objects’ via objc_[set,get]AssociatedObject

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Which Foundation collection would you use for frequent containsObject: tests?

A

NSSet (it’ll be faster than NSArray)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is required of classes that are to be used as dictionary keys?

Provide answers for both Objective C and Swift

A

Objective C: they must conform to NSCopying and implement copyWithZone:

Swift: they must conform to Hashable and implement var hashValue: Int { get }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is a key requirement when implementing the isEqual: method?

A

If two objects are equal, they must have the same hash value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

When would you use __block?

A

Normally variables are copied when used inside a block and so changes are not reflected outside of the block - but when using __block, such changes are visible outside too

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is a retain cycle?

A

A retain cycle is a situation when object A retains object B, and object B retains object A at the same time (there could be longer chains of objects too)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Explain messages vs methods in Objective C

A

Sending messages is more dynamic. Sending a message usually results in the corresponding method being called - but it doesn’t have to. Objects don’t have to respond to messages. Messages that an object responds to don’t have to be known at compile time

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Name a way to add visual effects (such as blur or vibrancy) to a user interface

A

Using a UIVisualEffectView in conjunction with UIBlurEffect or UIVibrancyEffect

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What’s the difference between UIModalPresentationFullScreen and UIModalPresentationOverFullScreen?

A

FullScreen removes the views beneath the presented view controller, whereas OverFullScreen does not (and hence they may still be visible in some form)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

When would you use NSValue?

A

When you need to wrap scalar types - e.g. ints, floats, chars, pointers, structs, object id references - in an object (so that they can be added to a collection, for example)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

When is a view controller’s preferredContentSize generally used?

A

When displaying the view controller’s content in a popover

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How do you determine which view controller presented a view controller (if any)?

A

Use the UIViewController property presentingViewController

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Should you call dismissViewControllerAnimated:completion: on the view controller you wish to dismiss, or the view controller that presented it?
The view controller that presented it
26
Name a built in way of evaluating a string containing an arithmetical expression such as "1 + 2 + 3"
NSExpression
27
Name a built in way of evaluating a string containing a logical expression such as "1 + 2 \> 2"
NSPredicate
28
Name the logical drawing space used by native drawing technologies such as Quartz, UIKit, and Core Animation (i.e. not pixels!)
Points
29
State the difference and relationship between points and pixels
Points are logical whereas pixels are physical. The system automatically maps points in the view’s coordinate space to pixels in the device coordinate space, but this mapping is not always one-to-one.
30
State the logical resolution of an iPhone 4
320 x 480 (points)
31
State the logical resolution of an iPhone 5
320 x 568 (points)
32
State the logical resolution of an iPhone 6
375 x 667 (points)
33
State the logical resolution of an iPhone 6 plus
414 x 736 (points)
34
State the logical resolution of an iPad
1024 x 768 (points)
35
What is the superclass of UIView?
UIResponder
36
What is the superclass of UIApplication?
UIResponder
37
What is the superclass of UIResponder?
NSObject
38
What is the superclass of UIWindow?
UIView
39
What does it mean for a UIWindow to be a key window?
The key window is the one that is designated to receive keyboard and other non-touch related events
40
How many UIWindows can be the key window at any time?
Only one window at a time may be the key window
41
How do you get a UIApplication's key window?
Via its keyWindow property
42
In general, how many UIWindows does an iOS app have?
Generally just one. However it is possible for an app to have more than one window (especially if it can display content on an external screen).
43
How do you get references to an application's windows?
Via the windows property that UIApplication instances have.
44
How do you get the singleton UIApplication instace for your app?
UIApplication.sharedApplication()
45
What is a window's root view controller? (As per the UIWindow rootViewController property)
The root view controller provides the content view of the window. Assigning a view controller to this property installs the view controller’s view as the content view of the window. If the window has an existing view hierarchy, the old views are removed before the new ones are installed.
46
How do you get a window's root view controller?
Via the rootViewController property on UIWindow instances
47
How do you get a view controller's navigation controller (if there is one)?
Via the UIViewController navigationController property
48
What is the superclass of UIViewController?
UIResponder
49
How do you get a view controller's split view controller (if there is one)?
Via the UIViewController.splitViewController property
50
How do you get a view controller's tab bar controller (if there is one)?
Via the UIViewController tabBarController property
51
How would you determine the best size of a UIView considering all constraints it holds and those of its subviews?
Using systemLayoutSizeFittingSize() and passing it one of: UILayoutFittingCompressedSize UILayoutFittingExpandedSize
52
When considering a UIView's subviews array, how does placement in the array affect the visible order on the screen (z order)?
The view at index 0 is the back-most view. The view at the highest index is the front-most view.
53
When considering the Interface Builder document outline, how does the vertical placement of views in the list relate to their z ordering?
The item at the top of the list is the back-most view. The item at the bottom of the list is the front-most view.
54
How do you get your application's documents directory?
By passing the values NSDocumentDirectory and NSUserDomainMask to the NSFileManager method URLsForDirectory:inDomains: ## Footnote This method returns an array of URLs - but on iOS there's only ever one element in the array.
55
Where should you store files on disk that you want to be persisted and backed up?
In the application's documents directory
56
Name the enumeration that represents the types of directories you may wish to access from an app (for example, the documents directory or caches directory)
NSSearchPathDirectory
57
Give a very rough outline of a strategy for having a popover on an adapting to a modal with navigation on iPhone
1. Setup popover presentation segue without nav con 2. In prepareForSegue set a delegate on the dest VC's popoverPresentationController 3. Use delegates' presentationController:viewControllerForAdaptivePresentationStyle to return a nav con
58
How do you get a view controller's popover presentation controller (if there is one)?
Using UIViewController's popoverPresentationController property
59
In a navigation controller's viewControllers array, at which index is the root view controller?
Index 0
60
In Core Data, what is the name of the resource that contains the definition of an application's data structure / schema?
The Managed Object Model
61
In Core Data, what is the name of the resource that contains the applications data (for example, the SQLite database)?
The Persistent Store
62
In Core Data, what is the name of the object that mediates between Persistent Store(s) and Managed Object Context(s) as per the Managed Object Model?
The Persistent Store Coordinator
63
Describe what a Managed Object Context is
* Single object space / scratchpad * Manages a collection of managed objects * (Internally consistent view of 1+ persistent stores) * Fetching, creating * Undo / redo
64
Can a managed object context have more than one managed object that represents a given record in a persistent store?
No - there can only be one
65
Describe what faulting means, with reference to Core Data
A fault is a placeholder object that represents a managed object that has not yet been fully realized, or a collection object that represents a relationship: * Managed object: an instance of the appropriate class (persistent variables are not yet initialized) * Relationship: a subclass of the collection class that represents the relationship
66
Describe uniquing, with reference to Core Data
Uniquing ensures that, in a given managed object context, an entry in a persistent store is associated with only one managed object. Without uniquing, you could end up with a context maintaining more than one object to represent a given record (and they could contain different and conflicting data).
67
What class would you use to parse decimal strings, currency strings, etc into numbers?
NSNumberFormatter. Here's an example of parsing a French-style decimal in Swift: ``` let formatter = NSNumberFormatter() formatter.locale = NSLocale(localeIdentifier: "fr") let number = formatter.numberFromString("1,34") ``` // number == 1.34
68
If your app has a settings bundle (i.e. uses the main iOS Settings app), where are the user settings stored?
In your app's NSUserDefaults
69
What is a plist?
A property list is a structured data representation used by Cocoa and Core Foundation as a convenient way to store, organize, and access standard types of data
70
What types of data can comprise a plist?
1. array (NSArray) 2. dictionary (NSDictionary) 3. string (NSString) 4. data (NSData) 5. date (NSDate) 6. number - integer (NSNumber) 7. number - floating point (NSNumber) 8. Boolean (NSNumber) ## Footnote Note that Core Foundation (CF\*) equivalents of the above can also be stored.
71
How would you store an instance of a custom class in a plist?
1. Have the class conform to NSCoding 2. Use a NSKeyedArchiver to convert objects of your class to NSData 3. The NSData can then be natively stored in the plist
72
What are the required methods when conforming to the NSCoding protocol?
- (id)initWithCoder:(NSCoder \*)decoder - (void)encodeWithCoder:(NSCoder \*)encoder
73
What protocol would you conform to when you want your classes to be able to be encoded and decoded (and archived and unarchived)?
NSCoding
74
Describe the NSCopying protocol. Name one notable case where classes are required to implement it.
The NSCopying protocol declares a method (copyWithZone:) for providing functional copies of an object. The meaning of “copy” can vary from class to class, but a copy must be a **functionally independent object with values identical to the original at the time the copy was made**. Notable case: objects used as NSDictionary keys must conform to NSCopying.
75
What types of data can you store in NSUserDefaults?
Property list (plist) types: 1. array (NSArray) 2. dictionary (NSDictionary) 3. string (NSString) 4. data (NSData) 5. date (NSDate) 6. number - integer (NSNumber) 7. number - floating point (NSNumber) 8. Boolean (NSNumber) Note that Core Foundation (CF\*) equivalents of the above can also be stored.
76
Briefly explain the difference between Foundation and Core Foundation
Foundation is an Objective-C API, which provides NSString, NSDictionary, etc. Core Foundation is a C API, which provides CFString, CFDictionary, etc.
77
Describe what the following function does: UIApplicationMain(argc, argv, principalClassName, delegateClassName)
This function is called to: 1. Create the application object 2. Create the application delegate 3. Set up the main event loop, including the app’s run loop, and begins processing events 4. Load any main nib/storyboard
78
The function UIApplicationMain() has a return type of int - but what does it return?
Nothing - the function never actually returns ## Footnote RR: the return type of int is most likely used to fit in with C's main() function, from where UIApplicationMain() is called
79
Explain Deployment Target and Base SDK
Deployment Target: the oldest version of iOS you're supporting Base SDK: the newest version of iOS you're supporting (this setting will generally be "Latest iOS")
80
What is a run loop?
* A run loop is an **event processing loop** (e.g. a WHILE) that you use to: * Schedule work * Coordinate incoming events * Every thread has an associated run loop object (including the application’s main thread) * Keeps the thread busy when there is work to do and puts it to sleep when there is none
81
When would you use a run loop?
The only time you need to run a run loop explicitly is when you create secondary threads for your application. The run loop for your application’s main thread is a crucial piece of infrastructure. As a result, the app frameworks provide the code for running the main application loop and start that loop automatically.
82
Describe the main queue (or "main dispatch queue")
* **Globally available** * **Serial** queue * Executes tasks on the application’s **main thread** (and so is a key synch point for an app) * Works with the application’s run loop to interleave execution of queued tasks with execution of other event sources attached to the run loop
83
List the types of dispatch queue
1. Serial (tasks executed one at a time) 2. Concurrent (tasks executed concurrently) 3. Main dispatch queue (globally available serial queue)
84
Describe the main event loop
* Run loop for the main thread * App continuously routes incoming events to objects for handling and, as a result, updates its appearance and state * Its primary input source receives events from the OS that are generated by user actions (e.g. tapping a view)
85
Describe LLVM
The LLVM Project is a collection of modular and reusable compiler and toolchain technologies. Despite its name, LLVM has little to do with traditional virtual machines. LLVM is an alternative to (say) GCC. *Clang* is a C/C++/Objective C "front end" to LLVM. Swift uses LLVM too.
86
Describe Clang
Clang is a C, C++, Objective C and Objective C++ front-end for the LLVM compiler. (Also: Clang has the Clang Static Analyzer, a source code analysis tool that finds bugs in C, C++, and Objective-C programs, which can be used from within Xcode)
87
Describe LLDB
The LLDB project builds on libraries provided by LLVM and Clang to provide a native debugger.​ LLDB is the default debugger in Xcode on Mac OS X and supports debugging C, Objective-C and C++ on the desktop and iOS devices and simulator. Swift uses LLDB too.
88
Describe the Objective-C Runtime
The Obj-C Runtime is a library that adds object oriented capabilities to C to create Obj-C. It essentially creates all the support structures that make OOP with Obj-C possible. Importing runtime.h lets you interact with the runtime via C calls, but Foundation provides a some access for Obj-C too. What can you do with it? All sorts of things from checking if a class responds to a selector to dynamically generating classes at runtime.
89
What framework would you use for accessing and manipulating calendar events and reminders?
EventKit
90
What is the relationship between Quartz 2D and Core Graphics?
The Quartz 2D API is part of the Core Graphics framework, so you may see Quartz referred to as Core Graphics or, simply, CG.
91
Give an overview of the layers in iOS from the Core OS up to Cocoa Touch
1. Cocoa Touch 2. Media 3. Core Services 4. Core OS
92
Describe the Cocoa Touch layer in iOS
The Cocoa Touch layer includes k​ey frameworks for building iOS apps, including: * UIKit * MapKit * EventKit UI * Message UI
93
Describe the Media layer in iOS
The Media layer contains the graphics, audio, and video technologies you use to implement multimedia experiences in your apps, including: * Core Graphics * Core Animation * Core Image * Core Text and TextKit
94
Describe the Core Services layer in iOS
The Core Services layer contains fundamental system services for apps, including: * Core Foundation and Foundation * Core Data * Core Motion * Core Location * EventKit
95
Describe the Core OS layer in iOS
The Core OS layer contains the low-level features that most other technologies are built upon. Even if you do not use these technologies directly in your apps, they are most likely being used by other frameworks. Frameworks include: * "System" * Core Bluetooth
96
Describe the class cluster pattern
Class clusters group a number of private concrete subclasses under a public abstract superclass. The grouping of classes in this way provides a simplified interface to the user, but behind the scenes, the abstract class is calling up the private subclass most suited for performing a particular task. Eg. depending on how you get hold of an NSString, it could actually be one of several private subclasses.
97
Name the two most common subclasses of NSCoder
NSKeyedArchiver and NSKeyedUnarchiver
98
Describe target-action
Target-action is a mechanism for communication between a control and another object. The control holds the information necessary to send a message to another object when an event occurs. This information consists of two items: * **Target**: the object to receive the message * **Action**: a selector identifying the method to be invoked
99
What is the superclass of UIControl?
UIView
100
What is the Responder Chain?
The responder chain is a series of linked responder objects (i.e. those based on UIResponder). It starts with the first responder and ends with the application object. If the first responder cannot handle an event, it forwards the event to the next responder in the responder chain.
101
What's the superclass of NSNumber?
NSValue
102
How are Swift basic types (see below) implemented behind the scenes? * integers * floating-point numbers * Booleans * strings * arrays * dictionaries
As structs
103
State the syntax for the following Swift type in its long form: String?
Optional〈String〉
104
What built-in class would you make a grid style view?
UICollectionView
105
What should you be aware of if your app is running in the background state?
It could be suspended at any time
106
How would you override the default behaviour of the active WiFi connection being closed after 30 minutes?
Set the Info.plist UIRequiresPersistentWifi key to YES.
107
List the states than an app can be in, including when it is running and when it is not.
1. Not running 2. Active 3. Inactive 4. Background 5. Suspended
108
What is a bundle?
A bundle is a directory in the file system that groups related resources together in one place.
109
What is contained in a typical app bundle?
1. App executable file 2. Information property list file 3. App icons 4. Launch images 5. Storyboards/nibs 6. Settings bundle 7. Resources: images/media 8. Localized content
110
State the difference between the following Swift operators: * == * ===
The double equals == performs an isEqual: type comparison wherease the triple equals === is an identity operator which you use to test whether two object references both refer to the same object instance ## Footnote (I.e. == is like isEqual: etc in Objective C, and === is like == in Objective C)
111
Can you subclass a Swift class from Objective C?
No
112
Describe 3 categories of background execution
1. Asking for more time (for short tasks) 2. Handing off downloads to the system 3. Specific background execution modes (as declared by the app) for specific tasks - e.g. playing audio, tracking location
113
State the definition of Swift's Array type
``` struct Array〈T〉 : MutableCollectionType, Sliceable { // Implementation } ```
114
Explain Content Hugging Priority
Higher priority means a view wants to hug its content and be its own size - it's less likely to stretch when the space it's in expands (Note that horizontal and vertical are treated separately)
115
Explain Content Compression Resistance Priority
Higher priority means a view has a greater resistance to compression - it's less likely to get compressed when the space it's in shrinks (Note that horizontal and vertical are treated separately)
116
Explain how Swift differs from Objective C with respect to creating mutable and immutable arrays and dictionaries
Objective C has different types that denote mutability (NSMutableArray and NSArray) whereas Swift uses var and let: var mutableArray = ["This", "is", "mutable"] let immutableArray = ["This", "is", "NOT", "mutable"]
117
State the 3 forms of closures in Swift
1. Global functions - named closures that do not capture any values 2. Nested functions - named closures that can capture values from their enclosing function 3. Closure expressions - unnamed closures with lightweight syntax that can capture values from their surrounding context
118
What is the first responder?
The first responder is a responder object that first receives various kinds of events in an application This includes key events, motion events, and action messages, among others. The first responder is typically the view in a window that an app deems best suited for handling an event. In order to become first responder, the responder must return YES for canBecomeFirstResponder.
119
What class would you use to work with regular expressions?
NSRegularExpression
120
What class would you use to detect and extract dates, addresses, links, and more from strings?
NSDataDetector (Note that it's limited to its predefined types)
121
Name a highly configurable class designed for scanning for and extracting subtrings and numeric values from loosely demarcated strings?
NSScanner
122
Name 4 options for scanning and extracting values from strings
1. NSString's "componentsSeparatedBy" methods - basic but great if your string is in the appropriate form 2. NSRegularExpression - powerful but can be cumberson 3. NSDataDetector - perfect for detecting and extracting dates, addresses, links, etc. Limited to its predefined types 4. NSScanner: Highly configurable and designed for scanning string and numeric values from loosely demarcated strings
123
Name the superclass of NSDataDetector
NSRegularExpression
124
What class would you use to do the following with a string? * Tokenize natural language strings into words * Determine their part-of-speech & stem * Extract names of people, places & organizations * Determine the languages & respective writing system
NSLinguisticTagger
125
In Interface Builder, how does an outlet collection differ from a regular outlet?
An outlet collection allows one outlet (in code) to be associated with a collection of Interface Builder views/controls. Instead of having properties in code representing every single control, you'd have a single array that represents the whole collection. You then wire up each of the controls to the array in question. This allows you to easily perform bulk operations on the controls (e.g. disable them all, etc).
126
Name a workaround that would allow you to use an object whose class does not conform to NSCopying as an NSDictionary key
Wrap the object in an NSValue using NSValue's valueWithNonretainedObject class/factory method. The NSValue you get back will conform to NSCopying.
127
What is Swift's equivalent of Objective C's id? How does Swift 'import' id?
The AnyObject protocol. Swift imports id as AnyObject.
128
Discuss GCD's dispatch\_apply() function
dispatch\_apply() acts like a for loop which executes iterations concurrently. It's sychronous, so just like a normal for loop, it returns only when all of the work is done. Example: ``` let q = dispatch\_get\_global\_queue(DISPATCH\_QUEUE\_PRIORITY\_LOW, 0) dispatch\_apply(10, q) { print($0) } ``` Prints something like 0324517689
129
State two options for concurrently processing an NSArray
1. Using NSArray's enumerateObjectsWithOptions:usingBlock: method and passing NSEnumerationConcurrent as an option 2. Using GCD's dispatch\_apply(), which is more low level and 'manual' than the above
130
How is NSArray bridged to Swift's array?
[AnyObject]
131
How is NSDictionary bridged to Swift's dictionary?
[NSObject: AnyObject]
132
Why does Swift need to represent Objective C's NSObject protocol as NSObjectProtocol (and not just NSObject)?
In Swift, the namespace of protocols and classes is unified (i.e. you cannot have both a class and a protocol named NSObject). In Objective C, you can have classes and protocols with the same name - as in the case of NSObject.
133
What protocol should you conform to if your class handles encoding and decoding instances of itself in a manner that is robust against object substitution attacks? What is the protocol does this protocol conform to?
NSSecureCoding NSSecureCoding conforms to NSCoding
134
State the replacement to UIWebView that was introduced with iOS 8. What framework is it part of? What advantages does it offer?
WKWebView (part of WebKit) * Performs better * Has the same JavaScript engine as Safari * Has streamlined communication between the app and webpage
135
Name a simple way you can check for the OS verion that was introduced in iOS 8
Use the isOperatingSystemAtLeastVersion method of NSProcessInfo. Swift example: ``` let minOS = NSOperatingSystemVersion(majorVersion: 8, minorVersion: 0, patchVersion: 0) if NSProcessInfo().isOperatingSystemAtLeastVersion(minOS) { println("iOS 8.0.0+") } ```
136
Describe the difference between Swift and Objective C in terms of closures/blocks capturing variables in the surrounding scope
Swift: such variables are mutable, and changes will be reflected outside the closure. Objective C: they are copied, and changes will not be reflected outside the closure. However you can use \_\_block to achieve the Swift-like behaviour.
137
List some of the things you can do using CFStringTransform
1. Strip accents and diacritics​ 2. Transliterate between orthographies 3. Encode/decode XML hex entities 4. Determine the Unicode standard name for special characters (including Emjoji)
138
What does CFStringTokenizer do?
1. Allows you to tokenize strings into words, sentences or paragraphs in a language-neutral way 2. Supports languages such as Japanese and Chinese that do not delimit words by spaces, as well as de-compounding German compounds 3. Provides language identification API
139
State some ways of identifying the language used in a string
1. Using NSLinguisticTagger to get an NSOrthography 2. Using CFStringTokenizer's language identification API 3. Using textInputMode.primaryLanguage on a UIResponder (gets the language the user is currently typing rather than analyzing a string though)
140
Describe how to setup a managed object context on a private queue, off the main queue/thread
[[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; * The MOC will setup its own private dispatch queue * To execute code on the private queue you simply use performBlock: / performBlockAndWait: * (Many operations are not thread safe so you will need to perform them on the MOC's queue)
141
Describe an approach to concurrency with Core Data and Managed Object Contexts that allows flexibility in terms of potentially temporary/cancellable operations and also keeps heavy lifting out of the main thread.
We take advantage of parent/child MOCs as introduced in iOS 5: 1. Master MOC connected to the persistent store with NSPrivateQueueConcurrencyType 2. Main thread’s MOC (NSMainQueueConcurrencyType) as a child of master 3. Intensive/background tasks done in worker MOCs which are setup as children of main MOC with the private concurrency type [1] simply writes to disk and nothing else. [2] is your single source of truth and is used for *all* user interaction. [3] are for non-user data manipulation.
142
Describe parent managed object contexts
1. MOCs have a parent store from which they retrieve data and through which they commit changes 2. Parent store can be a persistent store coordinator or another managed object context 3. Root of a MOC's ancestry must be a persistent store coordinator 4. When you save changes in a context, the changes are only committed “one store up" 5. Changes are not saved to the persistent store until the root context is saved 6. A parent does not pull changes from children before it saves
143
State 2 uses of parent/child managed object contexts
1. Performing background operations on a second thread or queue 2. Managing discardable edits, such as in an inspector window or view
144
List the size classes used within an app's UI
The following apply both horizontally and vertically: 1. Compact 2. Regular 3. (Any)
145
State the factors that determine the size class of a UI element
1. The screen size of the device 2. The orientation of the device 3. The portion of the screen available to the view controller. For example, when a split view controller displays both the master and detail controllers, neither controller has access to the full screen
146
With reference to an app's UI, what is a size class?
* A size class identifies a relative amount of display space for a UI element * There are two primary size classes: * Compact and Regular * Every screen or view defines a size class for both its horizontal and vertical dimensions - that is, its width and height * Hence we have four "abstract devices": * Compact-Compact * Compact-Regular * Regular-Compact * Regular-Regular
147
State the size classes of common devices and orientations
Regular width & regular height: * iPad portrait and landscape Regular width & compact height: * iPhone **6 plus** landscape Compact width & regular height: * iPhone (all) portrait Compact width & compact height: * iPhone (**all except 6 plus**) landsape
148
Describe Swift's NilLiteralConvertible
* NilLiteralConvertible is a protocol * Conforming types can be initialized with nil (the literal) * Swift's Optional type conforms to NilLiteralConvertible (as you might expect - but it's an interesting point)
149
State the definition of Swift's Optional type
``` enum Optional〈T〉 : Reflectable, NilLiteralConvertible { case None case Some(T) ``` ``` // Remaining implementation } ```
150
State the similarities and differences between weak and unowned references in Swift
Weak references and unowned references are both ways to resolve strong reference cycles when you work with properties of class type. They enable one instance in a reference cycle to refer to the other instance without keeping a strong hold on it. They can then refer to each other without creating a strong reference cycle. Use a **weak** reference whenever it is valid for that reference to become **nil** at some point during its lifetime. Use an **unowned** reference when you know that the reference will **never be nil** once it has been set during initialization.
151
In Swift, can you declare a weak reference as a constant value (i.e. using let)?
No. A weak reference cannot be declared as a constant. Weak references must be declared as variables, to indicate that their value can change at runtime.
152
Describe UIScreen
* A UIScreen object defines the properties associated with a hardware-based display * iOS devices have a main screen and zero or more attached screens * Use this class to obtain screen objects for each display attached to the device * Each screen object defines the bounds rectangle for the associated display and other interesting properties such as its brightness.
153
Give 4 examples of when you would use UIScreen
1. When you want to determine the size of the display in physical pixels (not points) 2. When you want to determine the brightness of a display 3. When creating a UIWindow whose dimensions you want to match those of a screen 4. When working with external displays
154
How do you associate a UIWindow with a UIScreen?
Via UIWindow's screen property (By default, all windows are created on the primary device screen)
155
Give two options for showing a UIWindow
1. Use the hidden property inherited from the UIView superclass 2. Call makeKeyAndVisible In general you would use [1] if your window does not need to handle events, and [2] if it does.
156
What is the superclass of UIScreen?
NSObject
157
Describe UITraitEnvironment
* UITraitEnvironment protocol * Provides access to iOS interface environment traits via the traitCollection property: * Horizontal and vertical size class * Display scale * User interface idiom * You can respond to changes in the interface environment (e.g. when an iPhone is rotated from portrait to landscape) via traitCollectionDidChange:
158
Which classes conform to the UITraitEnvironment protocol?
1. UIScreen 2. UIWindow 3. UIViewController 4. UIPresentationController 5. UIView
159
What is the superclass of UIPresentationController?
NSObject
160
What is the superclass of UIPopoverPresentationController?
UIPresentationController
161
Describe UITraitCollection (as obtained via UITraitEnvironment)
​UITraitCollection provides (read only) access to the following properties: 1. horizontalSizeClass 2. verticalSizeClass 3. displayScale (a float indicating whether retina or not) 4. userInterfaceIdiom (i.e. iPhone or iPad) You can also use it to compare trait collections.
162
Discuss viewWillLayoutSubviews
* viewWillLayoutSubviews is a method on UIViewController * When a view'€™s bounds change, the view adjusts the position of its subviews * This could happen as a result of change in orientation of the device * VCs can override this method to make changes before the view lays out its subviews * Default implementation does nothing
163
What should you do if programmatically creating views in an autolayout environment?
Call setTranslatesAutoresizingMaskIntoConstraints: and pass it a value of NO. Because the autoresizing mask naturally gives rise to constraints that fully specify a view’s position, any view that you wish to apply more flexible constraints to must be set to ignore its autoresizing mask using this method.
164
Explain the difference between the following UIView methods: * layoutSubviews * setNeedsLayout * layoutIfNeeded
* **Override** layoutSubviews to perform more precise layout of subviews * **Call** setNeedsLayout to invalidate the current layout of the receiver and trigger a subview layout update *during the next update cycle* * **Call** layoutIfNeeded to update the layout of subviews *immediately*
165
Discuss the UIContentContainer protocol
The methods of the UIContentContainer protocol help you **adapt the contents of your view controllers to size and trait changes**. All UIViewController and UIPresentationController objects provide default implementations for the methods of this protocol. When creating your own custom view controller or presentation controller, you can override the default implementations to make adjustments to your content. For example, you might use these methods to adjust the size or position of any child view controllers.
166
Explain the difference between the following UIView methods: * updateConstraints * setNeedsUpdateConstraints * updateConstraintsIfNeeded
* **Override** updateConstraints to setup constraints * **Call** setNeedsUpdateConstraints to indicate that the view's constraints need to be updated at some point in the future. The system will then call updateConstraints as part of its normal layout pass * **Call** updateConstraintsIfNeeded to update the constraints for the receiving view and its subviews in a more immediate fashion than setNeedsUpdateConstraints