Никита Корчагин - Programming Apple iOS with Objective-C

Post on 08-Aug-2015

65 views 4 download

transcript

Programming iOS with Objective-C

Nikita Korchagin

Developer

Today•Introduction

•Starting iOS programming

• iOS development

•Objective-C language - methods, properties, protocols...

•Model-View-Controller pattern

•Desktop vs. Mobile: what’s different

•Human Interface Guidelines

•Further steps: materials to read

How to start to develop for iOS?

Jedi way•Intel-based Mac (Mac Mini, MacBook Air/Pro, iMac, Mac Pro)

• Installed Mac OS X 10.7 «Lion» or higher

•XCode 6 with latest iOS SDK

•Own i-Device (iPhone/iPod Touch/iPad)

•Apple Developer program account ($99 per 1 year)

•Good knowledge of design patterns

•Objective-C knowledge OR

•Relevant experience in C or any strong-typed object-oriented language like Java/C#/C++

Alternative ways•Alternative IDE - AppCode (Mac, still requires Xcode to

be installed)

•Objective-C++ (kernel - C++, UI - Objective-C)

•PhoneGap/Titanium (cross-platform)

•Xamarin (.NET/C# - compiles to native code)

•C++ Marmalade SDK for Visual Studio

•Unity3D/Cocos2D-x for game development

•HTML5/CSS3/JavaScript for web applications

Swift

•Swift is a multi-paradigm, compiled programming language created by Apple Inc. for iOS and OS X development.

• It uses the Objective-C runtime, allowing C, Objective-C, C++ and Swift code to run within a single program.

•Swift was introduced at Apple's 2014 WWDC and Swift 2 at WWDC 2015. Initially a proprietary language, it was announced that Swift 2 would become open source supporting iOS, OS X and Linux.

•Swift supports the core concepts that made Obj-C flexible, notably dynamic dispatch, widespread late binding, extensible programming and similar features.

•Swift has added the concept of protocol extensibility, an extensibility system that can be applied to types, structs and classes, Apple promotes this as a real change in programming paradigms they refer to as protocol-oriented programming.

Objective-C

•Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.

• It is the main programming language used by Apple until 2014.

•Originally developed in the early 1980s, it was selected as the main language used by NeXT for its NeXTSTEP operating system.

•Objective-C is a thin layer on top of C, and moreover is a strict superset of C.

•All of the syntax for non-object-oriented operations (including primitive variables, pre-processing, expressions, function declarations, and function calls) are identical to that of C.

•Syntax for object-oriented features is an implementation of Smalltalk-style messaging.

Method Syntax

•Dash for instance method. Plus for class method.

- (NSArray *)shipsAtPoint:(CGPoint)bombLocation withDamage:(BOOL)damaged;

Instance methods•“Normal” methods you are used to.

•Can access instance variables inside as if they were locals.

•Can send messages to self and super inside.

•Both dispatch the message to the calling object, but use different implementations.

• If a superclass of yours calls a method on self, it will your implementation (if one exists).

•Example calling syntax:BOOL destroyed = [ship dropBomb:bombType at:dropPoint from:height];

Class methods•Used for allocation, singletons, utilities.+ (id)alloc; //makes space for an object of the receiver’s class (always pair w/init) + (id)motherShip; //returns the one and only, shared (singleton) mother ship instance + (int)turretsOnShipOfSize:(int)shipSize; // informational utility method

•Can not access instance variables inside.

•Messages to self and super mean something a little different. Both invoke only other class methods. Inheritance does work.

CalculatorBrain *brain = [[CalculatorBrain alloc] init]; Ship *theMotherShip = [Ship motherShip]; Ship *newShip = [Ship shipWithTurrentCount:5]; int turretsOnMediumSizedShip = [Ship turretsOnShipOfSize:4];

Instance variables•By default, instance variables are @protected (only the class and

subclasses can access).

•Can be marked @private (only the class can access) or @public (anyone can access).

@interface MyObject : NSObject { int foo; //protected @private int eye; //private @protected int bar; //protected @public int forum; //public int apology; //public @private int jet; //private }

Properties•Information from the previous slide doesn’t use in the modern

Objective-C!

•Use @property and “dot notation” to access instance variables.@interface MyObject : NSObject @property int eye; @end

•If you use the readonly keyword, only the getter will be declared@implementation MyObject @synthesize eye = _eye; //generate getters/setters - (int)eye { return _eye; } - (void)setEye:(int)eye { _eye = eye; } @end

Properties•It’s common to use dot notation to access ivars inside your class

• It’s not the same as referencing the instance variable directly.

•The latter calls the getter method (which is usually what you want for subclassability).

•There’s more to think about when a @property is an object. But it’s all about memory management.

int x = _eye; int y = self.eye;

Dynamic binding•All objects are allocated in the heap, so you always use a pointer.

•Decision about code to run on message send happens at runtime. Not at compile time. None of the decision is made at compile time.

•Static typing (e.g. NSString * vs. self) is purely an aid to the compiler to help you find bugs.

• If neither the class of the receiving object nor its superclasses implements that method: crash!

• It is legal (and sometimes even good code) to “cast” a pointer. But we usually do it only after we’ve used “introspection” to find out more about the object.

Introspection•So when do we use id? Isn’t it always bad? No, we might have a

collection (e.g. an array) of objects of different classes. But we’d have to be sure we know which was which before we sent messages to them. How do we do that? Introspection.

•All objects that inherit from NSObject know these methodsisKindOfClass: //returns whether an object is that kind of class (inheritance included) isMemberOfClass: //returns whether an object is that kind of class (no inheritance) respondsToSelector: //returns whether an object responds to a given method

•Arguments to these methods are a little tricky. Class testing methods take a Class. You get a Class by sending the class method class to a class :)

if ([obj isKindOfClass:[NSString class]]) { NSString *s = [(NSString *)obj stringByAppendingString:@"xyzzy"]; }

Introspection•Method testing methods take a selector (SEL).

•Special @selector() directive turns the name of a method into a selector.

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

• If you have a SEL, you can ask an object to perform it

if ([obj respondsToSelector:@selector(shoot)]) { [obj shoot]; }

[obj performSelector:shootSelector]; [obj performSelector:moveToSelector withObject:coordinate];

nil

•The value of an object pointer that does not point to anything

•Like “zero” for a primitive type (int, double, etc.). Actually, it’s not “like” zero: it is zero.

• NSObject sets all its instance variables to zero. Thus, instance variables that are pointers to objects start out with the value of nil.

•Sending messages to nil is (mostly) okay. No code gets executed.

Protocols•Similar to @interface, but no implementation

@protocol Foo - (void)doSomething; // implementors must implement this @optional - (int)getSomething; // implementors do not need to implement this @required - (NSArray *)getManySomethings:(int)howMany; // must implement @end

•Classes then implement it. They must proclaim that they implement it in their @interface

@interface MyClass : NSObject <Foo> ... @end

•You must implement all non-@optional methods

• Just like static typing, this is all just compiler-helping-you stuff It makes no difference at runtime.

Protocols

•Think of it as documentation for your method interfaces

•Number one use of protocols in iOS: delegates and dataSources

•The delegate or dataSource is always defined as an assign @property@property (assign) id <UIApplicationDelegate> delegate;

•Always assumed that the object serving as delegate will outlive the object doing the delegating.

Memory Management

Reference Counting

•How does it work? Simple set of rules everyone must follow.

•You take ownership for an object you want to keep a pointer to. Multiple owners for a given object is okay (common).

•When you’re done with an object, you give up that ownership. There’s a way to take “temporary” ownership too.

•When no one claims ownership for an object, it gets deallocated After that point, your program will crash if that object gets sent a message!

Reference Counting

•How does it work? Simple set of rules everyone must follow.

•You take ownership for an object you want to keep a pointer to. Multiple owners for a given object is okay (common).

•When you’re done with an object, you give up that ownership. There’s a way to take “temporary” ownership too.

•When no one claims ownership for an object, it gets deallocated After that point, your program will crash if that object gets sent a message!

Manual Reference Counting

Automatic Reference Counting

Temporary ownership

•So how does this “temporary ownership” thing work?

• If you want to give someone an object with the “option” for them to take ownership of it, you must take ownership of it yourself, then send the object the message autorelease (or obtain a temporarily owned object from somewhere else, modify it, then give it away).

•Your ownership will “expire” at some future time (but not before the current event is finished). In the meantime, someone else can send retain to the object if they want to own it themselves.

MVC

View Controllers

View Controller

•Class is UIViewController. It’s your Controller in an MVC grouping.

•VERY important property in UIViewController @property (retain) UIView *view;

•This is a pointer to the top-level UIView in the Controller’s View (in MVC terms)

•View Controllers have a “lifecycle” from creation to destruction. Your subclass gets opportunities to participate in that lifecycle by overriding methods

Controller of Controllers•Special View Controllers that manage a collection of other MVCs

• UINavigationController manages a hierarchical flow of MVCs and presents them like a “stack of cards”. Very, very, very commonly used on the iPhone

• UITabBarController manages a group of independent MVCs selected using tabs on the bottom of the screen

• UISplitViewController side-by-side, master->detail arrangement of two MVCs. iPad only

•Custom containers (iOS 5 and later)

Desktop vs. Mobile

What’s different?•Multitouch display & gestures

•Front and rear camera

•Speakers and microphone

•Location subsystem - GPS/GLONASS

•Magnetometer and compass

•G-sensor and accelerometer

•Bluetooth accessories

Network•Variants of connection

•GPRS

•EDGE

•3G/4G

•WiFi

•All these opportunities (except WiFi) are connection-lost-prone

•Cellular network connection is expensive

Screens

•Fullscreen applications

•Bigger UI elements for fingers

•Dark colors to reduce energy consumption

•Different resolutions (x1, x2 and x3)

•Assets for different resolutions

•Ergonomics

Resources•Every heavy application dramatically drains battery’s life

•Geolocation - GPS

•Networking

•Disk capacity is limited (8/16/32/64/… GB and no SD/microSD slot)

•Restricted multitasking (full introduced in iOS 7)

•Only a few types of content are supported

•UI is rendered using real-time thread and shouldn’t be blocked ever

Security mechanisms•Sandboxing - every application is isolated and runs under

restricted user’s account («jailed»)

• IPC is limited to URL schemas and extensions

•Personal data and passwords should be encrypted (Keychain) or not stored on the device at all

•HTTPS connections are preferred; certificate validation is needed

•Data on disk can be encrypted and protected by iOS

•Group policies can be established for iOS devices using configuration profiles

Creating and submitting the app

•Application should be tested thoroughly; crashes are forbidden

•Application should follow Apple’s Human Interface Guidelines

•Private API usage is forbidden

•Application can be deployed only to the device which is in the provisioning list

•Application’s binary is signed using developer’s private key

•Application is thoroughly tested during review process

Human Interface Guidelines

HIG

HIG

HIG

HIG

Bad UI/UX

Bad UI/UX

Bad UI/UX

Bad UI/UX

Tablets specific UI

Accessibility

Good UI/UX

Interface Builder HIG support

flat UI vs. skeuomorphism

Further steps

Q&A

Thanks for your attention!