iPhone dev intro

Preview:

DESCRIPTION

a simple intro to objc and iphone dev

Citation preview

iPhone程序开发基础Objective-C, UIKit

网络技术组 冯博bofeng@corp.netease.com

@vonbo10年9月6日星期一

Agenda

• overview

• objective-c

• iPhone UIKit

10年9月6日星期一

overview

10年9月6日星期一

First iPhone App

• Hello world!

10年9月6日星期一

Things we have

• Hello world!

10年9月6日星期一

开发流程

• 下载xcode和SDK

• 开发 & test with Simulator

• test with iPhone/iPod touch ($99)

• 提交到appstore

• 等待乔帮主审批

10年9月6日星期一

iPhone VS Android

10年9月6日星期一

objective-c

10年9月6日星期一

Objective C

• 概况及特性• 类定义,方法定义,方法调用• runtime

• foudation framework: values and collection classes

• 内存管理• category

• protocol

10年9月6日星期一

Sample Codehello world

10年9月6日星期一

10年9月6日星期一

objective c

• @表示扩展部分

• @interface, @implementation, @class

• @property, @synthesize

• @protocol

• NSString* str = @”hello world”

• 函数调用语法采用[receiver message]的方式

• 补充了C的不足,又没有C++复杂。如,不支持多类继承

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

Sample Codeclass and message

10年9月6日星期一

runtime

• id

• class & className

• respondsToSelector

• performSelector

• isKindOfClass (super class included)

• isMemberOfClass

• @selector

10年9月6日星期一

@selector

• SEL类型

• 类似C++编译时的函数签名

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

actionCGRect rect = CGRectMake(20, 20, 100, 30);

UIButton* myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];

myButton.frame = rect;

[myButton setTitle:@"my button" forState:UIControlStateNormal];

[myButton addTarget:self action:@selector(btnClick:) forControlEvents : UIControlEventTouchUpInside];

[self.view addSubview:myButton];

10年9月6日星期一

Sampleruntime & selector

10年9月6日星期一

Foundation Framework

• Value and Collection Classes

• User defaults

• Archiving

• Task, timers, thread

• File system, I/0

• etc ...

10年9月6日星期一

Value and Collection Classes

• NSString & NSMutableString

• NSArray & NSMutableArray

• NSDictionary & NSMutableDictionary

• NSSet & NSMutableSet

• NSNumber [a obj-c object wrapper for basic C type]

• (NSNumber* num = [NSNumber numberWithInt:3])

10年9月6日星期一

Sample Codecollection classes

10年9月6日星期一

内存管理

• 对象创建通过alloc和new实现,存在于堆上

• alloc&dealloc (C++:new&delete)

• but with ... 引用计数

10年9月6日星期一

内存管理• 当使用alloc,new方法或者copy创建一个对象时,对象的引用计数被设置为1.要增加对象的引用计数值,可以给对象发送一条retain消息。要减少对象的引用计数值,可以给对象发送一条release消息

• 当一个对象因其引用计数归0而即将被销毁时,Obj-C自动向对象发送一条dealloc消息。可以在自己对象中重写dealloc方法,释放已经分配的全部资源。但一定不要直接调用dealloc方法。

10年9月6日星期一

Sample Code看似简单,但“对象的所有权”还是有点复杂 ...

memory management

10年9月6日星期一

Getter & Setter@property & @synthesize

10年9月6日星期一

规则

• 当你使用new,alloc和copy方法创建一个对象时,该对象的引用计数值为1.当不再使用该对象时,你要负责向该对象发送一条release消息。

• 如果你保留了某个对象,你需要最终释放该对象。必须保持retain和release方法的使用次数相等。

10年9月6日星期一

but how to solve this ?- (Person*) getChild {

Person* child = [[Person alloc] init];

[child setName:@”xxxx”];

....

// will return ... [child release] or not ?

return child;

}

10年9月6日星期一

Autorelease

• NSAutoreleasePool* pool ...

• [object autorelease]

• 当给一个对象发送autorelease消息时,实际上是将该对象添加到NSAutoreleasePool中。当自动释放池被销毁时,会向该池中的所有对象发送release消息。

10年9月6日星期一

That’s why create pool first ...

int main(int argc, char* argv[]) {

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

// put your own code here ...

[pool release];

}

10年9月6日星期一

how to solve this ?- (Person*) getChild {

Person* child = [[Person alloc] init];

[child setName:@”xxxx”];

....

// will return ... [child release] or not ?

return [child autorelease];

}

10年9月6日星期一

关于Autorelease Pool

• 如何实现类似机制:• 创建全局的 NSMutableArray pool

• autorelease即向这个Array添加对象

• 当销毁pool时,依次向Array中的对象发送release消息

• 每一个线程维护一个autorelease pool的栈,当发送autorelease消息时,从此栈找到最顶层的pool,然后将对象放入此pool中

10年9月6日星期一

Autorelease Pool StackNSAutoreleasePool* poolFirst ..

for (int i=0; i < 10000; i++) {

NSAutoreleasePool* poolSecond ...

// have some autorelease object

// [object autorelease]

[poolSecond release];

}

// other code

[poolFirst release];

10年9月6日星期一

关于Autorelease Pool• 注意:• NSAutoreleasePool是一个普通对象,与其他对象一样遵从相同的内存管理规则,

• 创建时使用了alloc,结束时要release

• 稍有不同:Autorelease pool 不能retain,不能autorelease: [pool retain] or [pool autorelease]

• AutoreleasePool只是暂时存放待释放的对象,并非“垃圾回收机制”

• 由于被放入pool中的对象在pool被销毁之前不会释放内存,所以在iphone这种内存比较紧张的设备上,尽量使用release,少用autorelease

10年9月6日星期一

!大道至简,关于内存,这是所有规则 :• 当你使用new,alloc和copy方法创建一个对象时,该对象的引用计数值为1.当不再使用该对象时,你要负责向该对象发送一条release或autorelease消息。

• 当你通过任何其他方法获得一个对象时,则假设该对象的保留计数器值为1,而且已经被设置为自动释放,你不需要执行任何操作来确保该对象被清理。例如:[NSString stringWithString:@”objc”]

• 如果你保留了某个对象,你需要最终释放或自动释放该对象。必须保持retain和release方法的使用次数相等。

10年9月6日星期一

Category给现有类添加类方法

10年9月6日星期一

Sample Codecategory

10年9月6日星期一

用继承?某些类可能有陷阱,比如NSString这种 Class

Cluster ...

10年9月6日星期一

Sample Codesomething about class cluster ...

10年9月6日星期一

关于Category

• 用于方便的给类增加扩展方法• 不能增加成员变量• 名称冲突!即类别中的方法与现有的方法重名。当发生名称冲突的时候,类别具有更高的优先级。你的类别方法将完全取代初始方法,从而无法再使用初始方法。

10年9月6日星期一

协议 Protocol

• familiar with C++ virtual class

• familiar with Java’s interface

• 在协议中定义方法。当某个类采用此协议时,意味着该类承诺实现这个协议规定的方法。

• 协议中定义的方法当为@optional时,类可以不实现。当为@required时,不实现则编译时提示warning。(默认为required)

10年9月6日星期一

protocol

@protocol TwoMethod

- (void) oneMethod;

- (void) anotherMethod;

@end

10年9月6日星期一

Class & Protocol@interface MyClass : NSObject <TwoMethod> {

}

@end

@implementation MyClass

-(void) oneMethod {

// oneMethod’s implementation

}

- (void) anotherMethod {

// anotherMethod’s implementation

}

@end

10年9月6日星期一

Sample Codeprotocol

10年9月6日星期一

Objective C 总结• 概况及特性• 类定义,方法定义,方法调用• runtime (id, @selector, respondsToSelector ...)

• foudation framework: values and collection classes

• 内存管理 (三条原则)

• category (扩展类方法,class cluster的“陷阱”)

• protocol(接口方法)

10年9月6日星期一

Using Objective-C Now !

• without mac

• ubuntu:

• sudo apt-get install gnustep gnustep-devel

• bash /usr/share/GNUstep/Makefiles/GNUstep.sh

• GNUmakefile

• http://forum.ubuntu.org.cn/viewtopic.php?t=190168

10年9月6日星期一

iPhone UIKit

10年9月6日星期一

iPhone Application

• 组成部分 & 运行方式

• MVC

• Views (design & life cycle)

• Navigation based & Tab Bar based application

• very important TableView

• 数据的持久化存储

• Web service

10年9月6日星期一

10年9月6日星期一

UIApplication

• Every application must have exactly one instance of UIApplication (or a subclass of UIApplication). When an application is launched, the UIApplicationMain function is called; among its other tasks, this function create a singleton UIApplication object.

• The application object is typically assigned a delegate, an object that the application informs of significant runtime events—for example, application launch, low-memory warnings, and application termination—giving it an opportunity to respond appropriately.

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

UIApplicationMain

• delegateClassName

• Specify nil if you load the delegate object from your application’s main nib file.

• from Info.plist get main nib file

• from main nib file get the application’s delegate

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

UIControl

• UILabel

• UIButton

• UITableView

• UINavigatorBar

• ...

10年9月6日星期一

- design time

10年9月6日星期一

Demobutton click

10年9月6日星期一

Without IB ?create a button and bind event by code

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

Views• View是一块矩形区域,每一个view都有一个

superview,但可以有很多subviews

• 一个iphone app只有一个window,Views是存在一个window中,window其实也是一个view (top level)

• view的函数操作

• - (void)addSubview:(UIView *)view;

• - (void)removeFromSuperview;

• Superviews retain their subviews

• UIView的定位:CGRect (左上角的CGPoint和大小的CGSize)

10年9月6日星期一

View’s life cycle & hook function

• initWithNibName:bundle

• viewDidLoad

• viewWillAppear

• viewWillDisappear

• ...maybe viewDidUnload

• hook function

• shouldAutorotateToInterfaceOrientation

• didReceiveMemoryWarning

10年9月6日星期一

Navigation Controller

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

UINavigationController

• manages the currently displayed screens using the navigation stack

• at the bottom of this stack is the root view controller

• at the top of the stack is the view controller currently being displayed

• method:

• pushViewController:animated:

• popViewControllerAnimated:

10年9月6日星期一

DemoUINavigationController

10年9月6日星期一

TabBar Controller

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

UITabBarController

• implements a specialized view controller that manages a radio-style selection interface

• When the user selects a specific tab, the tab bar controller displays the root view of the corresponding view controller, replacing any previous views

• init with an array (has many view controllers)

10年9月6日星期一

DemoUITabBarController

10年9月6日星期一

Combine

• 一种常见的UI设计

• TabBarController Based + NavigationController

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

DemoCombine UITabBarController &

UINavigationController

10年9月6日星期一

TableView

• display a list of data

• Single column, multiple rows

• Vertical scrolling

• Powerful and ubiquitous in iPhone applications

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

Display data in Table View

• 容易想到的方案

• Table views display a list of data, so use an array

• [myTableView setList:myListOfStuff];

• 缺点:

• All data is loaded upfront

• All data stays in memory

• 更好的方案

• Another object provides data to the table view

• Not all at once

• Just as it’s needed for display

• Like a delegate, but purely data-oriented

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

DemoUITableView <UITableViewDataSource>

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

Selection

10年9月6日星期一

10年9月6日星期一

DemoUITableView <UITableViewDelegate>

10年9月6日星期一

UITabBar + UINavigation + UITableView !

一个常用的组合设计

TabBarController

NavigationController

TableViewController

10年9月6日星期一

DemoUITabBar + UINavigation + UITableView

10年9月6日星期一

数据持久化存储

• Propery Lists, NSUserDefaults

• SQLite

• Core Data

10年9月6日星期一

SandBox

• Why keep applications separate?

• Security

• Privacy

• Cleanup after deleting an app

10年9月6日星期一

Sample: /Users/xxx/library/Application Support/iPhone Simulator/4.0/Applications

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

Property Lists

• Convenient way to store a small amount of data

• Arrays, dictionaries, strings, numbers, dates, raw data

• Human-readable XML or binary format

• NSUserDefaults class uses property lists under the hood

• When Not to Use Property Lists

• More than a few hundred KB of data

• Custom object types

• Multiple writers (e.g. not ACID)

10年9月6日星期一

10年9月6日星期一

10年9月6日星期一

DemoSave data with NSUserDefaults

10年9月6日星期一

SQLite• Complete SQL database in an ordinary file

• Simple, compact, fast, reliable

• No server

• Great for embedded devices

• Included on the iPhone platform

• When Not to Use SQLite

• Multi-gigabyte databases

• High concurrency (multiple writers)

• Client-server applications

10年9月6日星期一

10年9月6日星期一

SQLite Obj-C Wrapper

• http://code.google.com/p/flycode/source/browse/trunk/fmdb

• A query maybe like this:

• [dbconn executeQuery:@"select * from call"]

10年9月6日星期一

10年9月6日星期一

Using Web Service• Two Common ways:

• XML:

• libxml2

• Tree-based: easy to parse, entire tree in memory

• Event-driven: less memory, more complex to manage state

• NSXMLParser

• Event-driven API: simpler but less powerful than libxml2

• JSON:

• Open source json-framework wrapper for Objective-C

• http://code.google.com/p/json-framework/

10年9月6日星期一

NSURLConnection

• NSMutableURLRequest

• - connectionWithRequest: delegate

• delegate method:

• – connection:didReceiveResponse:

• – connection:didReceiveData:

• – connection:didFailWithError:

• – connectionDidFinishLoading:

10年9月6日星期一

Demouse json-framework and NSURLConnection with hi-api

10年9月6日星期一

iPhone Application 总结

• 组成部分 & 运行方式

• MVC

• Views (design & life cycle)

• Navigation based & Tab Bar based application & TableView

• 数据的持久化存储 (sandbox, property list, sqlite)

• Web service

10年9月6日星期一

参考• 《Objective-C基础教程》

• 《The iPhone Developer’s Cookbook》

• 《Programming in Objective-C 2.0》

• 强大全面的官方文档• 力荐:Stanford iPhone dev course

• 使用iTunes在iTune Store中搜索cs193p,整套教程免费,mac和windows上均可用

10年9月6日星期一

Q & AThe End

10年9月6日星期一