Foundational Flashcards
how do we grow app to handle multiple MVC?
we use storyboards and we use “controllers of controllers”, for example, a UINavigationController.
how does “controllers of controllers” structure the multiple MVCs?
it points to a root view controller, it embeds an MVCs View inside its View, then a UI element in this View can segue to another MVC and its View is now embedded in the “controller of controllers” View
how do you “conditionally” segue?
call perform segue with identifier
when a segue happens, what goes on in my code?
source VC offers a chance to “prepare” the destination VC, before it comes on
how do we think of the new MVC we segue to?
we think of it as part of the “View” of the source VC: it communicates through delegation only in this case since target/action is not applicable here.
What goes on in your Controller when the device is rotated?
You can control whether the user interface rotates along with it using (BOOL) should autorotate to interface orientation
If you support an orientation, what will happen when rotated?
The frame of all subviews in your Controller’s View will be adjusted. The adjustment is based on their “struts and springs” you set in the size inspector in XCode. When a view’s bounds changes because its frame is altered, does drawRect: get called again? not by default, but you can change it so that it does redraw
When a view’s bounds changes because its frame is altered, does drawRect: get called again?
not by default, but you can change it so that it does redraw
What will happen when for a subview with “struts fixed to all four sides and both inner springs allow expansion”?
It grows and shrinks as its superview
’s bounds grow and shrink
What will happen when for a subview with “struts fixed to top, left, right sides (not bottom) and only the horizontal inner springs allow expansion (not vertical)”?
Grows and shrinks only horizontally as its superview grow and shrink and sticks to the top in its superview.
Redraw on bounds change?
By default, when your UIView’s bounds change, no redraw Instead, the “bits” of your view will be stretched or squished or moved. Often this is not what you want …
How do you change the default, meaning, when your UIView’s bounds change, how to you set redraw?
Use the UIView @property (nonatomic) UIViewContentMode contentMode; Assign value UIView Content Mode Redraw.
When is initWithFrame called?
When you instantiate with alloc] initWithFrame…
How do you override initWithFrame: ?
self = [super initWithFrame: aRect]
Why use awakeFromNib method ?
Because initWithFrame is NOT called for a UIView coming out of a storyboard, but awakeFromNib is. So you want to put set up stuff in awake from Nib.
Typical initFromFrame: code ?
self = [super initWithFrame:aRect];
[self setUp];
return self;
What are protocols?
Protocols are similar to @interface, but someone else does the implementing.
Where are protocols defined?
In its own header file, or in the header file of the class that wants other classes to implement it.
What does this mean? @protocol Foo
Implementors must implement Foo being declared here, as well as Other.
What does this mean: @interface MyClass : NSObject
MyClass is a kind of NSObject that implements the Foo protocol
id obj = [[MyClass alloc] init];
Declaring an id variable with a protocol requirement
What is the #1 use of protocols in iOS?
delegates and data source
@property (nonatomic, weak) id delegate;
@property (nonatomic, weak) id dataSource;
data source is just like delegate except it’s for delegating data
Why do Views commonly have a dataSource delegating provisions of data?
Because Views cannot own their own data.
How is protocol like static typing?
They’re both compiler-helping-you stuff. They make no difference at run-time. They’re documentation for you method interfaces as well.
What are some powerful ways to leverage the id type?
Use id in protocol
Is the class “UIGestureRecognizer” an abstract class? How do we use it?
Yes, it is an abstract class that we don’t instantiate from. We use the “concrete subclasses” of it like swipe, pinch, tap, pan.
What are the 2-sides to using a gesture recognizer?
- Adding a gesture recognizer to a UIView to ask it to recognize that gesture.
- Providing the implementation of a method to “handle” that gesture when it happens.
What is “panning”?
moving something around with your finger
Who handles recognized gestures?
The View would generally handle gestures to modify how the View is drawn.
The Controller would have to handle gestures that modified the Model.
In this code: UIPanGestureRecognizer *pangr =
[[UIPanGestureRecognizer alloc] initWithTarget:pannableView action:@selector(pan:)];
Is there an argument to pan: ? What is the argument sent?
This version of the action message takes one argument (which is the UIGestureRecognizer that sends the action),
but there is another version that takes no arguments if you’d prefer.
How does the state machine work inside gesture recognizers?
Gesture Recognizers sit around in the state Possible until they start to be recognized. Then they either go to Recognized (for discrete gestures like a tap). Or they go to Began (for continuous gestures like a pan). At any time, the state can change to Failed (so watch out for that). If the gesture is continuous, it’ll move on to the Changed and eventually the Ended state Continuous can also go to Cancelled state (if the recognizer realizes it’s not this gesture after all).
The base class, UIGestureRecognizer provides this @property:
@property (readonly) UIGestureRecognizerState state;
- (void)pan:(UIPanGestureRecognizer *)recognizer
{
if ((recognizer.state == UIGestureRecognizerStateChanged) ||
(recognizer.state == UIGestureRecognizerStateEnded)) {
We’re going to update our view every time the touch moves (and when the touch ends). This is “smooth panning.”
the pan gesture offers a translationInView method.
CGPoint translation = [recognizer translationInView:self];
What is translation? what is the view it refers to?
Translation is the cumulative distance this gesture has moved. Translation gives you a point that tells you the distance of the pan from the last point that was set in the gesture.
Specify which view’s coordinate system you want to be in with transitionInView:self, means this view’s coordinate system.
How to reset the cumulative distance or translation back to zero? And why?
Reset by setTranslation:CGPointZero inView:self
Now each time this is called, we’ll get the “incremental” movement of the gesture (which is what we want). If we wanted the “cumulative” movement of the gesture, we would not include this line of code.
Is Rotation gesture recognizer’s CGFloat rotation property in radians or degrees?
Radians
Is the Pinch gesture recognizer’s scale property read only?
No, you can reset each movement. Reset scale to 1 for the “incremental” effect of this gesture.
What is a view (i.e. a UIView subclass)?
A view (i.e. UIView subclass) represents a rectangular area
Defines a coordinate space
What can you do with a view?
You can use it to draw and handle events in that rectangle
How are views structured/related?
Hierarchical
A view has only one superview - (UIView *)superview
But can have many (or zero) subviews - (NSArray *)subviews
Subview order (in subviews array) matters: those later in the array are on top of those earlier.
The hierarchy is most often constructed in Xcode graphically Even custom views are added to the view hierarchy using Xcode
What about UIWindow?
UIWindow
The UIView at the top of the view hierarchy
Only have one UIWindow (generally) in an iOS application It’s all about views, not windows
Do we always use CGFloat for graphics in views?
Yes.
Just a floating point number, but we always use it for graphics.
What is a CGPoint?
C struct with two CGFloats in it: x and y.
CGPoint p = CGPointMake(34.5, 22.0); p.x+=20; //move right by 20 points
What is a CGSize?
C struct with two CGFloats in it: width and height. CGSize s = CGSizeMake(100.0, 200.0); s.height+=50;
What is a CGRect?
CGRect
C struct with a CGPoint origin and a CGSize size.
CGRect aRect = CGRectMake(45.0, 75.5, 300, 500);
Where is a view’s coordinate system origin?
upper left
What are the view’s coordinate system units?
Units are “points” not pixels. Usually you don’t care about how many pixels per point are on the screen you’re drawing on. Fonts and arcs and such automatically adjust to use higher resolution.
However, if you are drawing something detailed (like a graph, hint, hint), you might want to know. There is a UIView property which will tell you:
@property CGFloat contentScaleFactor; // returns pixels per point on the screen this view is on.
Explain the UIView’s property contentScaleFactor
The scale factor determines how content in the view is mapped from the logical coordinate space (measured in points) to the device coordinate space (measured in pixels). This value is typically either 1.0 or 2.0. Higher scale factors indicate that each point in the view is represented by more than one pixel in the underlying layer. For example, if the scale factor is 2.0 and the view frame size is 50 x 50 points, the size of the bitmap used to present that content is 100 x 100 pixels.
Explain UIView’s property CGRect bounds
bounds is your view’s internal drawing space’s origin and size.
The bounds property is what you use inside your view’s own implementation. It is up to your implementation as to how to interpret the meaning of bounds.origin
Explain UIView’s property for its superclass ie center and frame
center is the center of your view in your superview’s coordinate space. frame is a rectangle in your superview’s coordinate space which entirely contains your view’s bounds.size
You might think frame.size is always equal to bounds.size, but you’d be wrong …
Because views can be rotated (and scaled and translated too).
Views are rarely rotated, but don’t
misuse frame or center by assuming that.
When do you use bounds?
inside a view’s implementation with respect to its own coordinate system
When do you use frame and center?
Use frame and center to position the view in the hierarchy
These are used by superviews, never inside your UIView subclass’s implementation.
Most often you create views in XCode storyboard, but how would you do it in code?
Just use alloc and initWithFrame: (UIView’s designated initializer).
How do you use a view to do custom drawing?
Drawing is easy … create a UIView subclass & override 1 method - (void)drawRect:(CGRect)aRect;
Why you never ever call drawRect ?
Instead, let iOS know that your view’s visual is out of date with one of these
UIView methods:
- (void)setNeedsDisplay;
- (void)setNeedsDisplayInRect:(CGRect)aRect;
It will then set everything up and call drawRect: for you at an appropriate time
Obviously, the second version will call your drawRect: with only rectangles that need updates.
How do I implement drawRect?
Use the Core Graphics framework. The API is C (not object-oriented). Always use CGFloat.
Concepts:
- Get a context to draw into (iOS will prepare one each time your drawRect: is called)
- Create paths (out of lines, arcs, etc.)
- Set colors, fonts, textures, linewidths, linecaps, etc.
- Stroke or fill the above-created paths
What is the C function inside your drawRect: method to get the current graphics context that determines where your drawing goes, ie screen, pdf, printer..
CGContextRef context = UIGraphicsGetCurrentContext();
What are the 3 ways to effect transparency of a view?
- subview’s list order determines who’s in front
- alpha (default drawing is opaque)
- hide a view by setting it’s hidden property to YES
What do you have to do when using “subroutines” to help draw?
What if you wanted to have a utility method that draws something
You don’t want that utility method to mess up the graphics state of the calling method Use push and pop context functions.
Can you draw text and draw images?
Yes you can or more commonly we use UILabel for text, and UIImageView
What is the “push” mode in segue?
In this kind of segue, the destination vc is “pushed” onto the screen, while the source vc still exists but slides off. Segue always creates a brand-new vc object, never uses any existing on in the heap.
When the pinch first starts, meaning your fingers first set on screen, what is the scale value?
The scale starts out as 1, and can be reset to 1 for “incremental” zooming in/out.
As the pinch zooms out/in, the scale goes up or down?
As it goes out the scale goes up ie 1.07, 1.13. As it moves in, the scale decreases to say 0.9, 0.8.
How to you create a custom view in Xcode storyboard?
Drag out a generic View object and change it’s identity class to say GraphView, or whatever custom View class you made and want to subclass.
What is a UINavigationController’s toolbarItems @property?
It is an array of UIBarButtonItems
Where is the tool bar? Is it hidden by default?
At the bottom of the screen and yes it’s by default toolbarHidden is YES
Which view’s tool bar does the navigation controller, aka, the “controller of controller” show?
It show the tool bar of the view it’s currently embedding
How do you create a UIBarButtonItem?
Usually dragged out in Xcode, but can be created with various alloc/init methods.
A class is
a template for an object
An instance is
a manifestation of a class
A message is
something sent to a method to make it act
A method is
code invoked by a message
An instance variable is
object-specific storage
Superclass/subclass means
inheritance
A protocol is
non-class-specific methods
iOS is made up of
Cocoa Touch, Media, Core Services, and Core OS
Cocoa Touch is
Multi-touch, Core Motion, View Hierarchy, Localization, Controls, Alerts, Web View, Map Kit, Image Picker, Camera
MVC design means
divide your objects into 3 “camps”
model is what you app is (but not how it’s displayed)
controller is the UI logic of *how your model is presented to the user that uses views as minions to do the actual display and only the display
It’s all about managing communication between camps.
MVC
Describe view -> controller communication
blind and structured
target/action
when something happens in the UI, the view sends an “action to” the controller (the “target” is on the controller) like a button is pressed
delegate/data source
controller sets itself as a view’s delegate via protocol so that the view uses the controller as a data source or delegate of some action
What is the controller’s job?
To interpret/format Model data before giving it to the view
Can the model talk to the controller?
No, model should be UI-independent
What if the model has data to update?
let model use a “radio-station”-like broadcast mechanism called notification & kvo, and controller can “tune in” to interesting stuff
Usually we do not access instance variables directly in Objective-C. What do we use?
properties. A “property” is just the combination of a getter method and a setter method in a class.
The getter has the name of the property (e.g. “myValue”)
The setter’s name is “set” plus capitalized property name (e.g. “setMyValue:”)
Spaceship.h
#import “Vehicle.h”
@interface Spaceship : Vehicle
@end
#import superclass's header file, this is usually #import @interface class : superclass
Spaceship.m #import "Spaceship.h" @interface Spaceship() @end @implementation Spaceship @end
import our own header file
@interface class()
private declaration
@end
- (void)orbitPlanet:(Planet *)aPlanet atAltitude:(double)km;
- instance method
(void) return argument
orbitPlanet method name
: takes arguments
(Planet *) pointer to a Planet object
aPlanet argument variable name
atAltitude: takes argument
(double) primitive floating point number
km argument variable name
; end of method declaration
What does nonatomic mean?
nonatomic means its setter and getter are not thread-safe. That’s no problem if this is UI code because all UI code happens on the main thread of the application.
What does @synthesize do?
We almost always use @synthesize to create the implementation of the setter and getter for a @property
. It both creates the setter and getter methods AND
creates an instance variable/creates some storage to hold the value.
Calling getters and setters is such an important task, it has its own syntax: dot notation.
What is the common naming convention when you @synthesize and why?
_ (underbar) then the name of the property is a common naming convention.
All objects are always allocated on the heap. How do we access them?
So we always access them through a pointer. Always. @synthesize does NOT create storage for the object this pointer points to.
It just allocates room for the pointer. So you have to allocate and initialize the objects before use. You can do it in the getters.
What is the [ ] “square brackets” syntax used for?
The “square brackets” syntax is used to send messages.
Why properties?
Most importantly, it provides safety and subclassability for instance variables.
Also provides “valve” for lazy instantiation, UI updating, consistency checking (e.g. speed < 1), etc.
Why do you leave out @synthesize?
It is not required to have an instance variable backing up a @property (just skip @synthesize). Some @propertys might be “calculated” (usually readonly) rather than stored.
Why @property?
Pretty.
Makes access to @propertys stand out from normal method calls.
Synergy with the syntax for C structs (i.e., the contents of C structs are accessed with dots too). Syntactically, C structs look a lot like objects with @propertys.
What are the 2 big differences between C struct and objects?
With 2 big differences:
- we can’t send messages to C structs (obviously, because they have no methods)
- C structs are almost never allocated in the heap (i.e. we don’t use pointers to access them)
Explain strong/weak of iOS reference counting.
strong “keep this in the heap until I don’t point to it anymore” I won’t point to it anymore if I set my pointer to it to nil.
Or if I myself am removed from the heap because no one strongly points to me!
weak “keep this as long as someone else points to it strongly”
If it gets thrown out of the heap, set my pointer to it to nil automatically (if user on iOS 5 only).
What is the value of an object pointer that does not point to anything?
nil (Thus, instance variables that are pointers to objects start out with the value of nil.)
Like “zero” for a primitive type (int, double, etc.) Actually, it’s not “like” zero: it is zero.
nil
All instance variables start out set to ?
zero / or if they are pointers then / nil
Can be implicitly tested in an if statement if(obj){} //curly braces will execute if obj points to an object
nil
Sending messages to nil is (mostly) okay?
No code gets executed.
If the method returns a value, it will return zero.
int i = [obj methodWhichReturnsAnInt]; // i will be zero if obj is nil
Be careful if the method returns a C struct. Return value is undefined. CGPointp=[objgetLocation]; //pwillhaveanundefinedvalueifobjisnil
BOOL
Objective-C’s boolean “type” (actually just a typedef)
Why CGPoint doesn’t use * ?
CGPoint is a C struct, not a class! It looks like a class name, but notice no * because C structs are passed by value on the stack, not by reference in the heap.
What is the calling syntax for a class method?
[Class method]
Ship *ship = [Ship motherShip];
NSString *resultString =
[NSString stringWithFormat:@“%g”, result]; [[ship class] doSomething];
Explain self/super when in an instance versus in a class.
Instance:
self/super is calling instance self means “my implementation”
super means “my superclass’s implementation”
Class: self/super is this class self means “this class’s class methods” super means “this class’s superclass’s class methods”
What are the 3 ways to instantiate?
1. Asking other objects to create objects for you
NSString’s - (NSString *)stringByAppendingString:(NSString *)otherString;
- Not all objects handed out by other objects are newly created NSArray’s - (id)lastObject;
Unless the method has the word “copy” in it, if the object already exists, you get a pointer to it.
- Using class methods to create objects
Examples of using class methods to create objects.
NSString’s + (id)stringWithFormat:(NSString *)format, … UIButton’s + (id)buttonWithType:(UIButtonType)buttonType; NSMutableArray’s + (id)arrayWithCapacity:(int)count; NSArray’s + (id)arrayWithObject:(id)anObject;
How do you instantiate a stack?
Allocating and initializing an object from scratch
Doing this is a two step process: allocation, then initialization.
Both steps must happen one right after the other (nested one inside the other, in fact). Examples:
NSMutableArray *stack = [[NSMutableArray alloc] init];
CalculatorBrain *brain = [[CalculatorBrain alloc] init];
Explain allocating.
Heap allocation for a new object is done by the NSObject class method + (id)alloc It allocates enough space for all the instance variables (e.g., the ones created by @synthesize).
Explain initializing.
Classes can have multiple, different initializers (with arguments) in addition to plain init. If a class can’t be fully initialized by plain init, it is supposed to raise an exception in init. NSObject’s only initializer is init.