129
iPhone程序开发基础 Objective-C, UIKit 网络技术组 冯博 [email protected] @vonbo 10年9月6日星期一

iPhone dev intro

  • Upload
    vonbo

  • View
    1.517

  • Download
    1

Embed Size (px)

DESCRIPTION

a simple intro to objc and iphone dev

Citation preview

Page 1: iPhone dev intro

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

网络技术组 冯博[email protected]

@vonbo10年9月6日星期一

Page 2: iPhone dev intro

Agenda

• overview

• objective-c

• iPhone UIKit

10年9月6日星期一

Page 3: iPhone dev intro

overview

10年9月6日星期一

Page 4: iPhone dev intro

First iPhone App

• Hello world!

10年9月6日星期一

Page 5: iPhone dev intro

Things we have

• Hello world!

10年9月6日星期一

Page 6: iPhone dev intro

开发流程

• 下载xcode和SDK

• 开发 & test with Simulator

• test with iPhone/iPod touch ($99)

• 提交到appstore

• 等待乔帮主审批

10年9月6日星期一

Page 7: iPhone dev intro

iPhone VS Android

10年9月6日星期一

Page 8: iPhone dev intro

objective-c

10年9月6日星期一

Page 9: iPhone dev intro

Objective C

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

• foudation framework: values and collection classes

• 内存管理• category

• protocol

10年9月6日星期一

Page 10: iPhone dev intro

Sample Codehello world

10年9月6日星期一

Page 11: iPhone dev intro

10年9月6日星期一

Page 12: iPhone dev intro

objective c

• @表示扩展部分

• @interface, @implementation, @class

• @property, @synthesize

• @protocol

• NSString* str = @”hello world”

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

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

10年9月6日星期一

Page 13: iPhone dev intro

10年9月6日星期一

Page 14: iPhone dev intro

10年9月6日星期一

Page 15: iPhone dev intro

10年9月6日星期一

Page 16: iPhone dev intro

10年9月6日星期一

Page 17: iPhone dev intro

Sample Codeclass and message

10年9月6日星期一

Page 18: iPhone dev intro

runtime

• id

• class & className

• respondsToSelector

• performSelector

• isKindOfClass (super class included)

• isMemberOfClass

• @selector

10年9月6日星期一

Page 19: iPhone dev intro

@selector

• SEL类型

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

10年9月6日星期一

Page 20: iPhone dev intro

10年9月6日星期一

Page 21: iPhone dev intro

10年9月6日星期一

Page 22: iPhone dev intro

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日星期一

Page 23: iPhone dev intro

Sampleruntime & selector

10年9月6日星期一

Page 24: iPhone dev intro

Foundation Framework

• Value and Collection Classes

• User defaults

• Archiving

• Task, timers, thread

• File system, I/0

• etc ...

10年9月6日星期一

Page 25: iPhone dev intro

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日星期一

Page 26: iPhone dev intro

Sample Codecollection classes

10年9月6日星期一

Page 27: iPhone dev intro

内存管理

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

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

• but with ... 引用计数

10年9月6日星期一

Page 28: iPhone dev intro

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

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

10年9月6日星期一

Page 29: iPhone dev intro

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

memory management

10年9月6日星期一

Page 30: iPhone dev intro

Getter & Setter@property & @synthesize

10年9月6日星期一

Page 31: iPhone dev intro

规则

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

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

10年9月6日星期一

Page 32: iPhone dev intro

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日星期一

Page 33: iPhone dev intro

Autorelease

• NSAutoreleasePool* pool ...

• [object autorelease]

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

10年9月6日星期一

Page 34: iPhone dev intro

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日星期一

Page 35: iPhone dev intro

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日星期一

Page 36: iPhone dev intro

关于Autorelease Pool

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

• autorelease即向这个Array添加对象

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

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

10年9月6日星期一

Page 37: iPhone dev intro

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日星期一

Page 38: iPhone dev intro

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

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

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

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

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

10年9月6日星期一

Page 39: iPhone dev intro

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

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

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

10年9月6日星期一

Page 40: iPhone dev intro

Category给现有类添加类方法

10年9月6日星期一

Page 41: iPhone dev intro

Sample Codecategory

10年9月6日星期一

Page 42: iPhone dev intro

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

Cluster ...

10年9月6日星期一

Page 43: iPhone dev intro

Sample Codesomething about class cluster ...

10年9月6日星期一

Page 44: iPhone dev intro

关于Category

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

10年9月6日星期一

Page 45: iPhone dev intro

协议 Protocol

• familiar with C++ virtual class

• familiar with Java’s interface

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

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

10年9月6日星期一

Page 46: iPhone dev intro

protocol

@protocol TwoMethod

- (void) oneMethod;

- (void) anotherMethod;

@end

10年9月6日星期一

Page 47: iPhone dev intro

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

}

@end

@implementation MyClass

-(void) oneMethod {

// oneMethod’s implementation

}

- (void) anotherMethod {

// anotherMethod’s implementation

}

@end

10年9月6日星期一

Page 48: iPhone dev intro

Sample Codeprotocol

10年9月6日星期一

Page 49: iPhone dev intro

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

• foudation framework: values and collection classes

• 内存管理 (三条原则)

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

• protocol(接口方法)

10年9月6日星期一

Page 50: iPhone dev intro

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日星期一

Page 51: iPhone dev intro

iPhone UIKit

10年9月6日星期一

Page 52: iPhone dev intro

iPhone Application

• 组成部分 & 运行方式

• MVC

• Views (design & life cycle)

• Navigation based & Tab Bar based application

• very important TableView

• 数据的持久化存储

• Web service

10年9月6日星期一

Page 53: iPhone dev intro

10年9月6日星期一

Page 54: iPhone dev intro

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日星期一

Page 55: iPhone dev intro

10年9月6日星期一

Page 56: iPhone dev intro

10年9月6日星期一

Page 57: iPhone dev intro

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日星期一

Page 58: iPhone dev intro

10年9月6日星期一

Page 59: iPhone dev intro

10年9月6日星期一

Page 60: iPhone dev intro

10年9月6日星期一

Page 61: iPhone dev intro

UIControl

• UILabel

• UIButton

• UITableView

• UINavigatorBar

• ...

10年9月6日星期一

Page 62: iPhone dev intro

- design time

10年9月6日星期一

Page 63: iPhone dev intro

Demobutton click

10年9月6日星期一

Page 64: iPhone dev intro

Without IB ?create a button and bind event by code

10年9月6日星期一

Page 65: iPhone dev intro

10年9月6日星期一

Page 66: iPhone dev intro

10年9月6日星期一

Page 67: iPhone dev intro

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日星期一

Page 68: iPhone dev intro

View’s life cycle & hook function

• initWithNibName:bundle

• viewDidLoad

• viewWillAppear

• viewWillDisappear

• ...maybe viewDidUnload

• hook function

• shouldAutorotateToInterfaceOrientation

• didReceiveMemoryWarning

10年9月6日星期一

Page 69: iPhone dev intro

Navigation Controller

10年9月6日星期一

Page 70: iPhone dev intro

10年9月6日星期一

Page 71: iPhone dev intro

10年9月6日星期一

Page 72: iPhone dev intro

10年9月6日星期一

Page 73: iPhone dev intro

10年9月6日星期一

Page 74: iPhone dev intro

10年9月6日星期一

Page 75: iPhone dev intro

10年9月6日星期一

Page 76: iPhone dev intro

10年9月6日星期一

Page 77: iPhone dev intro

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日星期一

Page 78: iPhone dev intro

DemoUINavigationController

10年9月6日星期一

Page 79: iPhone dev intro

TabBar Controller

10年9月6日星期一

Page 80: iPhone dev intro

10年9月6日星期一

Page 81: iPhone dev intro

10年9月6日星期一

Page 82: iPhone dev intro

10年9月6日星期一

Page 83: iPhone dev intro

10年9月6日星期一

Page 84: iPhone dev intro

10年9月6日星期一

Page 85: iPhone dev intro

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日星期一

Page 86: iPhone dev intro

DemoUITabBarController

10年9月6日星期一

Page 87: iPhone dev intro

Combine

• 一种常见的UI设计

• TabBarController Based + NavigationController

10年9月6日星期一

Page 88: iPhone dev intro

10年9月6日星期一

Page 89: iPhone dev intro

10年9月6日星期一

Page 90: iPhone dev intro

DemoCombine UITabBarController &

UINavigationController

10年9月6日星期一

Page 91: iPhone dev intro

TableView

• display a list of data

• Single column, multiple rows

• Vertical scrolling

• Powerful and ubiquitous in iPhone applications

10年9月6日星期一

Page 92: iPhone dev intro

10年9月6日星期一

Page 93: iPhone dev intro

10年9月6日星期一

Page 94: iPhone dev intro

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日星期一

Page 95: iPhone dev intro

10年9月6日星期一

Page 96: iPhone dev intro

10年9月6日星期一

Page 97: iPhone dev intro

10年9月6日星期一

Page 98: iPhone dev intro

10年9月6日星期一

Page 99: iPhone dev intro

10年9月6日星期一

Page 100: iPhone dev intro

10年9月6日星期一

Page 101: iPhone dev intro

10年9月6日星期一

Page 102: iPhone dev intro

10年9月6日星期一

Page 103: iPhone dev intro

DemoUITableView <UITableViewDataSource>

10年9月6日星期一

Page 104: iPhone dev intro

10年9月6日星期一

Page 105: iPhone dev intro

10年9月6日星期一

Page 106: iPhone dev intro

Selection

10年9月6日星期一

Page 107: iPhone dev intro

10年9月6日星期一

Page 108: iPhone dev intro

DemoUITableView <UITableViewDelegate>

10年9月6日星期一

Page 109: iPhone dev intro

UITabBar + UINavigation + UITableView !

一个常用的组合设计

TabBarController

NavigationController

TableViewController

10年9月6日星期一

Page 110: iPhone dev intro

DemoUITabBar + UINavigation + UITableView

10年9月6日星期一

Page 111: iPhone dev intro

数据持久化存储

• Propery Lists, NSUserDefaults

• SQLite

• Core Data

10年9月6日星期一

Page 112: iPhone dev intro

SandBox

• Why keep applications separate?

• Security

• Privacy

• Cleanup after deleting an app

10年9月6日星期一

Page 113: iPhone dev intro

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

10年9月6日星期一

Page 114: iPhone dev intro

10年9月6日星期一

Page 115: iPhone dev intro

10年9月6日星期一

Page 116: iPhone dev intro

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日星期一

Page 117: iPhone dev intro

10年9月6日星期一

Page 118: iPhone dev intro

10年9月6日星期一

Page 119: iPhone dev intro

DemoSave data with NSUserDefaults

10年9月6日星期一

Page 120: iPhone dev intro

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日星期一

Page 121: iPhone dev intro

10年9月6日星期一

Page 122: iPhone dev intro

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日星期一

Page 123: iPhone dev intro

10年9月6日星期一

Page 124: iPhone dev intro

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日星期一

Page 125: iPhone dev intro

NSURLConnection

• NSMutableURLRequest

• - connectionWithRequest: delegate

• delegate method:

• – connection:didReceiveResponse:

• – connection:didReceiveData:

• – connection:didFailWithError:

• – connectionDidFinishLoading:

10年9月6日星期一

Page 126: iPhone dev intro

Demouse json-framework and NSURLConnection with hi-api

10年9月6日星期一

Page 127: iPhone dev intro

iPhone Application 总结

• 组成部分 & 运行方式

• MVC

• Views (design & life cycle)

• Navigation based & Tab Bar based application & TableView

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

• Web service

10年9月6日星期一

Page 128: iPhone dev intro

参考• 《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日星期一

Page 129: iPhone dev intro

Q & AThe End

10年9月6日星期一