iphone 개발 시작하기

Post on 21-Apr-2015

99 Views

Category:

Documents

7 Downloads

Preview:

Click to see full reader

DESCRIPTION

아이폰 개발을 시작 하는 사람을 위한 경험 나눔

TRANSCRIPT

iPhone Dev Experience

신철호 CRM/기술개발

• iPhone OS Overview

• Requirements

• Objective-C

• Xcode & IB

• iPhone App Dev Lifecycle

• References

today’s topic

iPhone OS Overview

Mac

iPhone

Core OSOS X Kernel

Mach 3.0

BSD

Sockets

Security

Power mgmt

Keychain

Certificates

File System

Bonjour

Core ServicesCollections

AddressBook

Networking

File Accesses

SQLite

Core Location

Net Services

Threading

Preferences

URL utilities

MediaCore Audio

Coco AL

Audio Mix

Audio Record

Video Playback

JPG,PNG,TIFF

PDF

Quartz(2D)

Core Animation

OpenGL ES

Cocoa touchMultiTouch Events

MultiTouch Controls

Accelerometer

View Hierarchy

Localization

Alerts

Web View

People Picker

Image Picker

Controllers

CocoaTouch Architecture

Requirement

• Hardware

• Development Environment

Intel Based Mac + iPhone + SDK

Objective-C

• Class & Object

• Memory Management

• Foundation Classes

• Debugging

Objective-C 란?

• 브래드 콕스가 Smalltalk의 특징들을 C에 추가해서 만든 언어

• 클래스들과 메시지 전송 메커니즘 추가

Object

• OOP(객체 지향 프로그래밍)는 객체를 중심으로 작성

• 객체는 데이터(data)와 데이터를 조작하는 특정 동작/연산(operation)으로 이루어 진다.

• 이러한 동작을 객체의 method, 메소드가 조작하는 객체의 데이터를 instance variable라고 한다.

• Objective-C는 동적인 언어이다. runtime 시에 객체나 메소드가 변할 수있다.

Object Messaging

• Objective-C에서는 해당 객체에 메시지를 보낸다라고 표현한다.

• 메세지를 받을 객체에 메세지를 보내면 리시버가 적절한 메소드를 찾아서 불러주는 구조

메시지 호출• Defining a method

• Invoking a method

- (void)setWidth:(float)w height:(float)h{ width = w; height = h; }

[myBox setWidth:42.0 height:3.5];

Class

• Encapsulation : keep implementation private and separate from interface

• Polymorphism : different objects, same interface

• Inheritance : hierarchical organization, share code, customize or extend behaviors

Class 정의• Interface File : Interface File로 한 클래스의 메소드와 인스턴스 변수를 선언하고, 어느 슈퍼클래스로부터 상속을 받는지를 기입한다.

• Implementation File : 실제 클래스를 정의하는 부분으로 메소드를 구현하는 부분이다. 보통 구현 파일인 *.m파일에 구현된다.

• Objective-C는 ANSI C 또는 C++과 같이 쓰일수 있으며 C++과 함께 쓰인 ObjC는 .mm 확장자를 사용한다.

Interface File• #import는 C의 전처리기 #include와 비슷하

다.

• 하지만 #import는 파일을 한 번만 인클루드 하도록 한다.

• @interface와 @end 사이에 인터페이스를 정의하는 부분으로 클래스를 선언한다.

• 왼쪽 예제의 Person이라는 오브젝트를 NSObject를 상속받아 선언한 것이다.

• NSObject 클래스는 Objective-C 의 최상위 root class 이다.

• Objective-C를 위한 기본적인 프래임웍과 오브젝트의 사이에서 벌어지는 작동이 정의 되어 있다.

// <Person.h> #import <Cocoa/Cocoa.h> @interface Person:NSObject { @protected: NSString *name; int age; @private: NSString *sex; } // method declarations -(NSString *)name; -(void)setName:(NSString *)value; -(int)age; -(void)setAge:(int)age; -(BOOL)canLegallyVote; @end

Instance Variable Scope

Directive Meaning

@private 오직 클래스 내에서만 접근 가능

@protected 자신의 클래스와 상속 받은 클래스에서만 사용 가능

@public 어디에서든 모두 접근 가능

@package framework 안에서는 @public으로 밖에서는 @private로 사용 가능

Implementation File• Person.h 헤더파일을 import

• 헤더파일에 선언된 메서드 들을 @implementation과 @end 사이에 메서드를 구현한다.

• Objective-C에서는 메서드 명에 get을 붙이지 않고 변수명과 동일하게 사용을 하도록 한다.

• + 가 붙은 메서드는 클래스 멤버함수로써 기존의 static 함수와 같이 클래스의 인스턴스가 아닌 클래스 자체에 속하는 함수로 별도로 인스턴스를 만들지 않고도 호출할수 있다.

• - 가 붙은 메서드는 일반 멤버함수이며 클래스의 인스턴스를 상대로 작업하는 함수이다.

// <Person.m> #import "Person.h"

@implementation Person // method implementations - (int)age{ return age; } - (void)setAge:(int)value{ age = value; } - (BOOL)canLegallyVote{ return (age > 17); } //and other as declared in header... @end

Default Data Type• id - 객체를 가리킴. 인스턴스에 대한 포인터.

• Class - 클래스 자체에 대한 포인터

• SEL - 메소드의 이름을 선택하기 위한 선택자

• IMP - id를 리턴하는 메소드의 구현부에 대한 포인터

• BOOL - 이진값. YES 또는 NO

• nil - NULL object

• IBOutlet - 인터페이스 빌더가 .h 파일에서 클래스 선언을 읽을 때 클래스 선언을 인터페이스 빌더에 인식시키는 키워드

• IBAction - 인터페이스 빌더는 IBAction으로 시작하는 함수를 이벤트 핸들러로서 인식.

self and super• 객체가 자기자신을 나타내고자 할때는 self 라는 키워드를 사용한다.

• 객체의 슈퍼 클래스를 나타낼때는 super 키워드를 사용한다.

• 아래의 예제는 상위클래스의 doSomething 메소드에 메세지를 보내는것.

// (like "this" int C++) - (void) doSomething { [self doSomethingElseFirst]; ... }

- (void)doSomething{ [super doSomething]; ... }

@property

• 기본적인 역할은 get/set 함수를 자동으로 선언해 주는 것 // Test.h file @interface Test : NSObject{ NSString *name; } @property NSString *name; //method @end

• @synthesize를 사용하면 컴파일러가 자동으로 만들어 준다.

// .h @interface MyInteger : NSObject{ NSInteger value; } @property(readonly) NSInteger value; @end // .m @implementation MyInteger @synthesize value; @end

• retain : 외부에서 그 객체를 release 하더라도 객체가 메모리 해제되지 않도록 유지하기 위한 것

• copy : copy 는 값을 복사해서 새로운 객체를 만들기 때문에 인자로 전달되는 객체가 자주 변경될 소지가 있는 경우에 적합

• assign : 외부에서 참조 카운트를 감소시켜 객체가 해제될 위험이 있기 때문에 주의해서 사용@property (nonatomic, retain) UIImage* img;@property (nonatomic, copy) NSString* name;@property (nonatomic, assign) BOOL enable;

Selector

• Class의 메소드들을 색인

• 컴파일러는 각 메소드들의 이름을 테이블에 넣어두고 각각의 고유한 아이디를 만듬.

• 컴파일된 selector는 SEL 이라는 특별한 타입으로 처리

• friend object의 gossipAbout 메소드에 aNeighbor 파라미터 입력

• selector 적용 예

[friend gossipAbout:aNeighbor];

[friend performSelector:@selector(gossipAbout:) withObject:aNeighbor];

Category

• 목적• 클래스를 연관된 몇개의 그룹으로 나누어서 관리

• 기존의 클래스를 상속 받지 않고 새로운 메써드를 추가 가능

• informal protocol을 구현할때 사용

• 장점• category를 이용하면 class 층을 만드는 것을 줄일 수 있다.

• NSString에 메소드 추가하기 #import <Foundation/Foundation.h> @interface NSString (FirstLetter) - (NSString *)firstLetter; @end

#import "FirstLetter.h" @implementation NSString (FirstLetter) - (NSString *)firstLetter { // } @end

Protocol

• 자바의 인터페이스와 유사• 반드시 구현해야 하는 메소드 집합을 선언• 필수 메서드와 옵션 메서드 선언 가능- protocol 정의@protocol ProtocolName // method declarations@ned

- protocol 선언@interface ClassName (Categoryname) <protocol_1, protocol_2>

- protocol 사용Protocol *myProtocol = @protocol(MyProtocol);

Memory Management

• Reference counter

• 모든 객체는 소유 횟수(retain count)를 가지고 있다.

• alloc 메서드가 객체를 생성하면 소유 횟수는 1 증가

• retain 메시지는 소유 횟수 1 증가

• release 메시지는 소유 횟수 1 감소

• 인스턴스 생성 alloc

• 초기화 init

• 중첩 사용 가능

NSMutableArray *foo; foo = [NSMutableArray alloc]; [foo init];

NSMutableArray *foo; foo = [[NSMutableArray alloc] init];

• retain : 해당 오브젝트에 대한 reference counter 증가 시킴

• release : 사용중이던 인스턴스에 대한 메모리 확보 포기. Reference counter 하나 감소시킴.

• dealloc : reference counter가 0이 되었을때 자동으로 불리워짐.

• retainCount : reference counter의 현재값을 확인.

• NSAutoreleasePool 클래스 사용

• autorelease는 그 메세지의 receiver가 나중에 release 되게 표시를 해 놓는 역할

• 메소드 내에서 사용되는 일시적인 인스턴스들을 처리하기 위한 메모리 관리의 한 형식

• NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

자동 해제

가비지 컬렉션 지원• Unsupported

• 가비지 컬렉션을 사용하지 않습니다.

• Supported (-fobjc-gc)

• 가비지 컬렉션과 이전의 retain/release를 병행해서 사용할 수 있습니다.

• Required (-fobjc-gc-only)

• 가비지 컬렉션만 사용하고 이전의 retain, release를 사용하지 않습니다.

Foundation Classes

Foundation Frameworks

• Value and Collection classes

• User defaults

• Archiving

• Notifications

• Undo manager

• Task, Timers, Threads

• File system, pipes, I/O, bundles

NSObject

• Root Class

• Implements many basics

‣ Memory management- -(id)init,-(id)new- -(id)retain - -(id)release- -(id)dealloc

‣ Object equality- -(BOOL)isEquals:(id)anObject

NSString

• Unicode String Buffer

• @”...”

• most commonly used -(id)initWithFormat:(NSString *)format...-(id)stringByAppendingString:

(NSString *)aString

Format String

• Similar to printf, but with %@ added for object

• Used for logging

NSString aString = @”Xcode”;

NSString *log = [NSString stringWithFormat:@”It’s ‘%@’”,aString];

NSLog(@”I am a %@, I have %d items”,[array className], [array count]);

NSArray

• List of other object pointer

• Common NSArray methods

• nil termination!!

• NSNotFound returned for index if not found

-(unsigned)count

-(id)objectAtIndex:(unsigned)index

-(id)lastObject

-(BOOL)containsObject:(id)object

-(unsigned)indexOfObject:(id)object

NSMutableArray

• NSMutableArray subclasses NSArray

• Common NSMutableArray Methods-(void)addObject:(id)object

-(void)addObjectsFromArray:(NSArray *)otherArray

-(void)insertObject atIndex:(unsigned)index

-(void)removeAllObjects

-(void)removeObject:(id)object

-(void)removeObjectAtIndex:(unsigned)index

NSMutableArray *array = [NSMutableArray array];

[array addObject:@”Red”];

[array addObject:@”Blue”];

[array removeObjectAtIndex:0];

Debugging

DebuggingLife After NSLog

Two Ways to Debug

• Not So Awesome : NSLog‣ Useful in some situations

like debugging race conditions‣ Just inspecting variables

• Awesome : Use Debugger‣ Best way to fix bugs‣ Set breakpoints, step through code, inspect

variables

• Add & Set breakpoints• view your call stack per thread• view the value of variables• Step in to, out of

General Tasks

Debugging Window

Xcode & IB

Xcode

• 자동완성/제안 기능 향상

• 블럭

• Focus ribbon

• Code folding

• Message bubbles

• 스냅샷

• 리펙토링

Documentation

Interface Builder

Instrument

iPhone App Dev Lifecycle

Typical Development Cycle

iPhone Development Cycle

iPhone App Dev Lifecycle

Production DefinitionList of features

오디오북 재생; 빠르게듣기, 천천히 듣기, 원하는 지점으로 이동, 일시정지, 재생. 오디오북 목록 보기,오디오북 재생중 책 내용보기, 책 내용 검색하기. 오디오북 상세 정보 보기, 과거 재생 상태 기억. 과거 재생 목록 기억,재생중 광고 표시, 2배속으로 듣기, 최근 인기 오디오북 보기, 공짜 오디오북 보기, 오디오북 벨소리로 저장하기.

Production DefinitionList of features

오디오북 재생; 빠르게듣기, 천천히 듣기, 원하는 지점으로 이동, 일시정지, 재생. 오디오북 목록 보기,오디오북 재생중 책 내용보기, 책 내용 검색하기. 오디오북 상세 정보 보기, 과거 재생 상태 기억. 과거 재생 목록 기억,재생중 광고 표시, 2배속으로 듣기, 최근 인기 오디오북 보기, 공짜 오디오북 보기, 오디오북 벨소리로 저장하기.

Define A Solution!not list of features.

“책 보기와 책읽기를 함께 하는 쓰기편한 오디오북”

오디오북 재생; 빠르게듣기, 천천히 듣기, 원하는 지점으로 이동, 일시정지, 재생. 오디오북 목록 보기,오디오북 재생중 책 내용보기, 책 내용 검색하기. 오디오북 상세 정보 보기, 과거 재생 상태 기억. 과거 재생 목록 기억, 재생중 광고 표시, 2배속 으로 듣기, 최근 인기 오디오북 보기, 공짜 오디오북 보기, 오디오북 벨소리로 저장하기.

Assessing Application Types

Prototyping

Design

Coding

limsk

ojsong

chshin

Organizing Contents

• Focus on Data• Drill down into greater

detail

Audiobooks

A Controller for each Screen

List Controller Detail Controller Play Controller

Book List(1st depth)

Book Sub(2nd depth)

Audio Play(3rd depth)

UINavigationController

• Navigation Bar

• Stack of view Controller

View Controller’s Role

• Load views

• Connect the model to the view

• Manage the flow of the app

The Application Delegate

• Load the Models

• Load the first view controller

- (void)applicationDidFinishLaunching:(UIApplication *)application {! NSString *path = [[NSBundle mainBundle] bundlePath];! NSString *finalPath = [path stringByAppendingPathComponent:@"data.xml"];! NSData *xmlData = [[NSData alloc] initWithContentsOfFile:finalPath];! NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:xmlData];! XMLParser *parser = [[XMLParser alloc] initXMLParser]; ... [window addSubview:[navigationController view]];! [window makeKeyAndVisible];}

How it’s work

• User Action

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { mvController.bpvController.aBookFile = [aBook.contents objectAtIndex:indexPath.row]; mvController.bpvController.aBook = aBook; mvController.bpvController.bplvController = mvController.bplvController;! [self.navigationController pushViewController:mvController.bpvController animated:YES];}

How it’s work

• User Action

• Data Creation

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { mvController.bpvController.aBookFile = [aBook.contents objectAtIndex:indexPath.row]; mvController.bpvController.aBook = aBook; mvController.bpvController.bplvController = mvController.bplvController;! [self.navigationController pushViewController:mvController.bpvController animated:YES];}

How it’s work

• User Action

• Data Creation

• Push

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {! mvController.bpvController.aBookFile = [aBook.contents objectAtIndex:indexPath.row];! mvController.bpvController.aBook = aBook;! mvController.bpvController.bplvController = mvController.bplvController;! [self.navigationController pushViewController:mvController.bpvController animated:YES];}

Testing

• Using the Simulator

- to rapidly debug- Using the Static Analysis (in xcode 3.2)

- Using the Instruments

• Be aware of Simulator & Device

- Security.framework- Network, Processing performance

Deploy To the AppStoreApply to the paid iPhone developer program. & Setup your profile, team profile(code sign too.)

iTunes Connect add your application

iTunes Connect add application detailed description

iTunes Connect 57x57 icon.png, Default.png, 512x512 icon, etc

Status : In Review can be published.

Prepare Binary for upload

• In Xcode

- Check the project info & target info- Set Active SDK to “Device”- Set Active Configuration to Release- Set Code Signing Identity- Set Code Signing Distribution Provisioning Profile- Zip my .app using Finder

References

• WWDC 09 Session Video

• #100 User Interface Design• #603 In-House App Development• #125 Effective iPhone App Architecture• #702 Publishing on the App Store

• CS193P : #1 #2

top related