35
АРХИТЕКТУРА И MVC Лекция 2 TTLabs - iOS Labs Thursday, December 15, 11

iOS Architecture and MVC

  • Upload
    -

  • View
    7.831

  • Download
    2

Embed Size (px)

DESCRIPTION

iOS Development course at initLab by TenTouch

Citation preview

Page 1: iOS Architecture and MVC

АРХИТЕКТУРА И MVCЛекция 2

TTLabs - iOS LabsThursday, December 15, 11

Page 2: iOS Architecture and MVC

КОМУНИКАЦИЯ

• http://www.slideshare.net/mignev/tag/ios-development-at-initlab

• Google Groups

• Skype: dani_rangelov

• Facebook

• Mail: [email protected]

Thursday, December 15, 11

Page 3: iOS Architecture and MVC

APPSTORE

Thursday, December 15, 11

Page 4: iOS Architecture and MVC

APPSTORE

Thursday, December 15, 11

Page 5: iOS Architecture and MVC

APPSTORE

Thursday, December 15, 11

Page 6: iOS Architecture and MVC

APPSTORE

Thursday, December 15, 11

Page 7: iOS Architecture and MVC

APPSTORE

Thursday, December 15, 11

Page 8: iOS Architecture and MVC

APPSTORE

Thursday, December 15, 11

Page 9: iOS Architecture and MVC

CORE OS

Core OS

Core ServicesSystem

• Threading (POSIX threads)• Networking (BSD sockets)• File-system access• Standard I/O• Bonjour and DNS services• Locale information• Memory allocation

Security FW

External Accessory FW

Accelerate FW

iOS is a Mac OS X which is a UNIX - like system

Media

Cocoa Touch

Thursday, December 15, 11

Page 10: iOS Architecture and MVC

CORE SERVICES

Core OS

Core Services Collections• NSArray• NSDictionary• NSSet

File Access

Threading

Address Book

High-Level Features

• ARC (Automatic Reference Counting)

• iCloud• GCD(Grand Central

Dispatch)• In-App Purchase• SQLite

Media

Cocoa Touch

Networking

Preferences

Thursday, December 15, 11

Page 11: iOS Architecture and MVC

MEDIA LAYER

Core OS

Core Services

Media

Cocoa TouchCore Audio

AirPlay Audio Recording

Core Animation

Quartz (2D) Audio Mixing

Video Playback OpenAL

JPEG, PNG, TIFF PDF

Thursday, December 15, 11

Page 12: iOS Architecture and MVC

COCOA TOUCH

Core OS

Core Services

High-Level Features

• Push Notifications• Storyboard• Local Notifications• Printing• Gesture Recognition• File Sharing

Media

Cocoa Touch

Game Kit

View Controllers

Events (Touch)

iAd

Map Kit

UIKit

Thursday, December 15, 11

Page 13: iOS Architecture and MVC

MVC - MODEL VIEW CONTROLLER

Controller

Описание

Как да се изобрази

Запазва състоянието на апликациятаПоказва функционалносттаСъобщава на View за промени

Определя поведениетоПроменя модела

Определя кое View получава touches

Изобразяване

Изпраща действията на потребителя към controllerИзисква промяна на моделаИзобразява модела /render/

ViewModel

Thursday, December 15, 11

Page 14: iOS Architecture and MVC

MVC - MODEL VIEW CONTROLLER

View

Controller

Model

Thursday, December 15, 11

Page 15: iOS Architecture and MVC

MVC - MODEL VIEW CONTROLLER

Model View

Controller

Outlet

Delegate

Notify

Notification / KVO

Thursday, December 15, 11

Page 16: iOS Architecture and MVC

APPLICATION EVENTSFigure 2-1 Key objects in an iOS app

Data Objects Document

Data Model ObjectsData Model ObjectsViews and UI ObjectsData Model ObjectsData Model Objects

View Controller

Model

Controller

EventLoop

View

UIWindowUIApplication

Custom Objects

System Objects

Either system or custom objects

Application Delegate

Table 2-1 The role of objects in an iOS app

DescriptionObject

You use the UIApplication object essentially as is—that is, without subclassing. Thiscontroller object manages the app event loop and coordinates other high-‐level appbehaviors. Your own custom app-‐level logic resides in your app delegate object, whichworks in tandem with this object.

UIApplicationobject

The app delegate is a custom object created at app launch time, usually by theUIApplicationMain function. The primary job of this object is to handle statetransitions within the app. For example, this object is responsible for launch-‐timeinitialization and handling transitions to and from the background. For informationabout how you use the app delegate to manage state transitions, see “Managing AppState Changes” (page 35).

In iOS 5 and later, you can use the app delegate to handle other app-‐related events.The Xcode project templates declare the app delegate as a subclass of UIResponder.If the UIApplication object does not handle an event, it dispatches the event to yourapp delegate for processing. For more information about the types of events you canhandle, see UIResponder Class Reference.

App delegateobject

22 The Core Objects of Your App2011-10-12 | © 2011 Apple Inc. All Rights Reserved.

CHAPTER 2

Core App Objects

Thursday, December 15, 11

Page 17: iOS Architecture and MVC

MVC - MODEL VIEW CONTROLLER

Controller

View

backgroundColor  propertyhidden  propertyalpha propertyuserInteractionEnabled  propertymultipleTouchEnabled  propertyautoresizingMask  propertyautoresizesSubviews  property– initWithFrame:– addSubview:– bringSubviewToFront:– sendSubviewToBack:– removeFromSuperview+ beginAnimations:context:+ commitAnimations

- viewDidLoad- viewDidUnload– viewWillAppear:– viewDidAppear:– viewWillDisappear:– viewDidDisappear:– shouldAutorotateToInterfaceOrientation:- willRotateToInterfaceOrientation:– didReceiveMemoryWarning– dismissViewControllerAnimated:– presentModalViewController:animated:– dismissModalViewControllerAnimated:

CoreDataNSArrayNSDictionaryplist

Model

Thursday, December 15, 11

Page 18: iOS Architecture and MVC

ОСНОВИ НА OBJECTIVE C@“Hello World!”

Thursday, December 15, 11

Page 19: iOS Architecture and MVC

OBJECTIVE C

• Комбинация межди C & Smaltalk

• Superset на С

• Компилира С и С++ класове

•NeXTSTEP (NS)

• Apple

•Objective C

Thursday, December 15, 11

Page 20: iOS Architecture and MVC

XCODE

Thursday, December 15, 11

Page 21: iOS Architecture and MVC

THE APP LAUNCH CYCLEFigure 3-2 Launching an app into the foreground

Foreground

Your code

User taps app icon

main()

UIApplicationMain()

application:didFinishLaunchingWithOptions:

Load main UI file

Initialize the app

EventLoop

Launch Time

Handle events

Activate the app

Switch to a different app

applicationDidBecomeActive:

If your app is launched into the background instead—usually to handle some type of background event—thelaunch cycle changes slightly to the one shown in Figure 3-‐3. The main difference is that instead of your appbeingmade active, it enters the background state to handle the event and then is suspended shortly afterward.When launching into the background, the system still loads your app’s user interface files but it does notdisplay the app’s window.

38 Managing App State Changes2011-10-12 | © 2011 Apple Inc. All Rights Reserved.

CHAPTER 3

App States and Multitasking

Foreground

Thursday, December 15, 11

Page 22: iOS Architecture and MVC

APPLICATION STATES

Table 3-1 App states

DescriptionState

The app has not been launched or was running but was terminated by the system.Not running

The app is running in the foreground but is currently not receiving events. (It may beexecuting other code though.)

An app usually stays in this state only briefly as it transitions to a different state. The onlytime it stays inactive for any period of time is when the user locks the screen or the systemprompts the user to respond to some event, such as an incoming phone call or SMS message.

Inactive

The app is running in the foreground and is receiving events. This is the normal mode forforeground apps.

Active

The app is in the background and executing code. Most apps enter this state briefly on theirway to being suspended. However, an app that requests extra execution time may remainin this state for a period of time. In addition, an app being launched directly into thebackground enters this state instead of the inactive state. For information about how toexecute code while in the background, see “Background Execution and Multitasking” (page51).

Background

The app is in the background but is not executing code. The system moves apps to this stateautomatically and does not notify them before doing so. While suspended, an app remainsin memory but does not execute any code.

When a low-‐memory condition occurs, the system may purge suspended apps without noticeto make more space for the foreground app.

Suspended

Figure 3-1 State changes in an iOS app

Foreground

Inactive

Not running

Active

Inactive

Background

Suspended

Background

36 Managing App State Changes2011-10-12 | © 2011 Apple Inc. All Rights Reserved.

CHAPTER 3

App States and Multitasking

Thursday, December 15, 11

Page 23: iOS Architecture and MVC

RUN LOOP

• вход към програмата

main.m

Thursday, December 15, 11

Page 24: iOS Architecture and MVC

.H ( HEADER FILE)

• публични методи

• публични променливи

AppDelegate.h

Thursday, December 15, 11

Page 25: iOS Architecture and MVC

.M (IMPLEMENTATION FILE)

• описание на методите

AppDelegate.m

Thursday, December 15, 11

Page 26: iOS Architecture and MVC

ВИВОДЕ МЕТОДИ

• instance

• class

Thursday, December 15, 11

Page 27: iOS Architecture and MVC

ОСНОВЕН ОБЕКТ

•- (id)init;

•+ (id)alloc;

•- (void)dealloc;

•- (id)copy;

NSObject

Thursday, December 15, 11

Page 28: iOS Architecture and MVC

MEMORY MANAGEMENT

• retain

• release

• вески обект, който притежаваме трябва да бъде освободен, когато свършим работата си с него

Thursday, December 15, 11

Page 29: iOS Architecture and MVC

APPLICATION SANDBOX

• собствени файлове

• няма достъм по чужди

• сигурност

Figure A-1 Sandbox directories in iOS

App Sandbox

Documents

Library

tmp

MyApp.app

App

App Sandbox

App ...App Sandbox

App ...

......

Important: The purpose of a sandbox is to limit the damage that a compromised app can cause to thesystem. Sandboxes do not prevent attacks from happening to a particular app and it is still your responsibilityto code defensively to prevent attacks. For example, if your app does not validate user input and there is anexploitable buffer overflow in your input-‐handling code, an attacker could still hijack your app or cause it tocrash. The sandbox only prevents the hijacked app from affecting other apps and other parts of the system.

Keychain Data

A keychain is a secure, encrypted container for passwords and other secrets. The keychain is intended forstoring small amounts of sensitive data that are specific to your app. It is not intended as a general-‐purposemechanism for encrypting and storing data.

Keychain data for an app is stored outside of the app’s sandbox. When the user backs up app data usingiTunes, the keychain data is also backed up. Before iOS 4.0, keychain data could only be restored to the devicefrom which the backup was made. In iOS 4.0 and later, a keychain item that is password protected can berestored to a different device only if its accessibility is not set tokSecAttrAccessibleAlwaysThisDeviceOnly or any other value that restricts it to the current device.Upgrading an app does not affect that app’s keychain data.

For more on the iOS keychain, see “Keychain Services Concepts” in Keychain Services Programming Guide.

Security 1172011-10-12 | © 2011 Apple Inc. All Rights Reserved.

APPENDIX A

The iOS Environment

Thursday, December 15, 11

Page 30: iOS Architecture and MVC

XCODE PROJECT

Thursday, December 15, 11

Page 31: iOS Architecture and MVC

ЗА СЛЕДВАЩИЯТ ПЪТПодгряване

Thursday, December 15, 11

Page 32: iOS Architecture and MVC

DATA MODEL

•NSString (NSMutableString)•NSNumber•NSData (NSMutableData)•NSValue•NSDate•NSArray (NSMutableArray)•NSDictionary (NSMutableDictionary)•NSSet (NSMutableSet), NSOrderedSet

(NSMutableOrderedSet), NSIndexSet (NSMutableIndexSet)

Thursday, December 15, 11

Page 33: iOS Architecture and MVC

BUILDING AN INTERFACE USING UIKIT VIEWS

Note: You can also incorporate custom views into your UIKit view hierarchies. A custom view is a subclassof UIView in which you handle all of the drawing and event-‐handling tasks yourself. For more informationabout creating custom views and incorporating them into your view hierarchies, see ViewProgrammingGuidefor iOS.

Figure 2-‐3 shows the basic structure of an app whose interface is constructed solely using view objects. Inthis instance, the main view spans the visible area of the window (minus the scroll bar) and provides a simplewhite background. The main view also contains three subviews: an image view, a text view, and a button.Those subviews are what the app uses to present content to the user and respond to interactions. All of theviews in the hierarchy are managed by a single view controller object.

Figure 2-3 Building your interface using view objects

Application controller layer

View layer

Window View

ButtonImage View Text View

View Controller

In a typical view-‐based app, you coordinate the onscreen views using your view controller objects. An appalways has one view controller that is responsible for presenting all of the content on the screen. That viewcontroller has a content view, which itself may contain other views. Some view controllers can also act ascontainers for content provided by other view controllers. For example, a split view controller displays thecontent from two view controllers side by side. Because view controllers play a vital role in viewmanagement,understand how they work and the benefits they provide by reading View Controller Programming Guide foriOS. For more information about views and the role they play in apps, see View Programming Guide for iOS.

Building an Interface Using Views and OpenGL ES

Games and other apps that need high frame rates or sophisticated drawing capabilities can add viewsspecifically designed for OpenGL ES drawing to their view hierarchies. The simplest type of OpenGL ES appis one that has a window object and a single view for OpenGL ES drawing and a view controller to managethe presentation and rotation of that content. More sophisticated applications can use a mixture of bothOpenGL ES views and UIKit views to implement their interfaces.

The User Interface 292011-10-12 | © 2011 Apple Inc. All Rights Reserved.

CHAPTER 2

Core App Objects

Thursday, December 15, 11

Page 34: iOS Architecture and MVC

СТРУКТУРИ

• CGPoint

• CGSize

• CGRect = CGPoint, CGRect

Thursday, December 15, 11

Page 35: iOS Architecture and MVC

БЛАГОДАРЯ!

Thursday, December 15, 11