2009年9月9日 星期三

Quartz introduction

drawRect:
drawRect method of UIVew is called when a view needs to redraw itself
we usually add drawing code in this function

2009年9月5日 星期六

install ipa

from cydia,
install app: AppSync
restart ipod

thread & lock

- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;


create new thread to do something

- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg;


sleep

[NSThread sleepForTimeInterval:0.5]


lock:

ex:

NSLock *testLock = [[NSLock alloc] init];

[testLock lock];

[testLock unlock];

[testLock release];

UILabel

adjust line number:
can adjust from interface builder

2009年9月3日 星期四

ipod touch 破解方法

1. download redsn0w-mac_0.8
2. run redsnow
3. choose iPod2,1_3.0_7A341_Restore.ipsw
4. plugin ipod , close ipod
5. let iphone enter DFU mode ( 按住home & 電源 10秒 ,接著按home for some time)
6. if the screen show "waiting for reboot", unplug ipod & plug ipod again

2009年8月27日 星期四

UIViewController

originally in view of A controller,
then show view of B controller:
[self presentModalViewController:testViewController animated:YES];
[testViewController release];

jump back to view of A controller
[self dismissModelViewControllerAnimated:YES];

UIButton

ex:
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
backButton.frame = CGRectMake(380, 260, 80, 30);
[backButton setTitle:@"Back" forState:UIControlStateNormal];
[backButton addTarget:self action:@selector(backButtonClicked:)
forControlEvents:UIControlEventTouchUpInside];

2009年8月26日 星期三

core animation

three basic steps for core animation:
1. beginAnimations
2. setAnimationDuration
3. commitAnimations

shorter word to access app delegate

#define AppDelegate (MyAppDelegate *)[[UIApplication sharedApplication] delegate]


then use AppDelegate in the code


do something in the future

1. execute function in the future

- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay;

ex: [self performSelector:@selector(sing:) withObject:nil afterDelay:1.4];


2. use timer

(NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;

ex: [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(test:) userInfo:nil repeats:YES];
note:
to delete timer, use invalidate method
ex:
-(void)test:(NSTimer*)timer
{
[timer invalidate];
}

2009年8月25日 星期二

iphone view size

UIInterfaceOrientationLandscapeLeft:

w:480 h:320

2009年8月18日 星期二

modify view class for view controller

from view controller's xib,
click on view,
from inspector panel, click information ,
change class to the view class you want

2009年8月13日 星期四

game kit bluetooth connection problem

try
method 1:
turn off wifi

method 2:
restart iphone

2009年8月12日 星期三

trigger iphone vibrate

1. include AudioToolBox.framework

2.
#import
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

2009年8月4日 星期二

get current time

NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |
NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit |
NSSecondCalendarUnit;
NSDate *date = [NSDate date];
NSDateComponents *dateComponents = [calendar components:unitFlags
fromDate:date];
NSInteger year = [dateComponents year];
NSInteger month = [dateComponents month];
NSInteger day = [dateComponents day];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];

[calendar release];

2009年8月1日 星期六

animation delegate

1. initial
// if want to change something, such as move a UIImageView,
// then pass this UIImageView as context argument
[UIView beginAnimations:@"test" context:nil];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:
@selector(animationDidStop:finished:context:)];
[UIView commitAnimations];

2. when animation finish, animationDidStop is called

- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished
context:(void *)context

NSThread

do sth on main thread , and wait until done

ex:

[self performSelectorOnMainThread:@selector(loadPhoto) withObject:nil waitUntilDone:YES];

2009年7月30日 星期四

2009年7月5日 星期日

take photo for iphone screen

按下上方的開機鍵+中間的方塊鍵

2009年6月14日 星期日

combine UITabBarController & UINavigationController

1. add UITabBarController

2. for "Tab Bar Controller" , set first tab's controller as Navigation Controller

3. set view of first tab as "firstView.nib"

4. set first tab's view's controller as "firstViewController"


2009年6月10日 星期三

Game kit

2 functions:
(1) p2p connectivity:
create an ad-hoc Bluetooth network
(2) in-game voice

use GKSession class

not support first-generation iphone & ipod touch

each peer has a peerID

use displayNameForPeer to get peer's name

GKSessionDelegage: handle connection request

data handler: receive data from peer

3 session mode:
(1)server:
advertise sessionID
GKSessionModeServer
(2)client:
search for sessionID
(3)peer:
advertise sessionID & search for sessionID
GKSessionModePeer

2009年6月4日 星期四

sqlite

import data to table from csv file:
1. sqlite3 testDatabase
create database testDatabase

2. create table testTable(name String primary key, job String);

3. .mode csv

4. .import ./test.csv testTable

5. select * from testTable;
show content of testTable

6. drop table testTable;
delete testTable


support sqlite in project:
(1)add framework
framework location:
/Developer/Platforms/iPhoneOS.plateform/Developer/SDKs/iPhoneOS2.2.1.sdk/usr/lib/libsqlite3.0.dylib
(2) import "/usr/include/sqlite3.h"

2009年6月3日 星期三

dial phone number

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://+886223699148"]];


call 02-23699148

2009年5月26日 星期二

UIToolBar

add UIToolBar:
default center: 160, 438
default size: 320, 44
ex:
UIToolBar *toolbar = [[UIToolBar alloc] initWithFrame: CGRectMake(0, 0, 320, 44)];
toolbar.barStyle = UIBarStyleDeafult;
toolbar.center = CGPointMake(160, 438);


2009年5月20日 星期三

設定app icon

icon name:
project -> edit active target -> build -> packaging -> Product Name

2009年5月16日 星期六

UITableView

problem:
table is in view A, when row in table is selected, jump to view B
then jump back to view A, the row is still selected( in blue color)

solution:
in viewWillAppear method of view A:

NSIndexPath *selection = [self.tableView indexPathForSelectedRow];

if(selection)

{

[self.tableView deselectRowAtIndexPath:selection animated:YES];

}

[self.tableView reloadData];

UITextField

set font size in IB:
menu --> font --> show fonts

2009年4月21日 星期二

setHTTPBodyStream

remember to set "Content-Length"

2009年4月8日 星期三

life cycle of iphone app

1.
main.m:
main() --> call UIApplicationMain


2.
application delegate
applicationDidFinishLaunching is called

3.
loading app's main nib file
In info.plist, key NSMainNibFile defines main nib file name
main nib file usually contains a window object, app delegate object, etc





2009年4月4日 星期六

create view controller

1. In xcode, create view controller MyViewController.m

2. For IB, create MyView.xib

3. In IB, set file's owner as MyViewController
connect file owner's view outlet to view window

2009年4月3日 星期五

add view method

method 1: with interface builder
1. create a subclass of UIView: newView

2. create a view xib: newView.xib

3. In IB, set view's class as newView

4. In xCode, add new view
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"newView" owner: self
options:nil];
UIView *view = [nib objectAtIndex: 1];
[self.view addSubview:view];
note: use the index for array of nib to get specific object, such as view

method 2: all within xCode:
CGRect newViewFrame = CGRectMake(0, 0, 50, 50);
UIView *newView = [[UIView alloc] initWithFrame:newViewFrame];
newView.backgroundColor = [UIColor blueColor];
[self.view addSubview:newView];

2009年4月2日 星期四

find memory leak with clang

  • Make sure the project default settings are “debug” and “simulator”
  • Close Xcode
  • open a terminal window and “cd” to the project directory
  • run rm -rf /tmp/scan-build*
  • run rm -rf build/;scan-build --view xcodebuild
  • Open Xcode and fix errors

2009年3月28日 星期六

install app on iphone

0. install .p12 file first

1. go to iphone developer program portal

2. create an app id for new app

3. enter device name & device id(can get from xcode's organizer window) for iphone

4. get an certificate

5. enter profile name

6. download profile

7. drag downloaded profile to xcode's organizer window

8. download certificate file(only first time needed)

9. double click on certificate file to install certificate (only first time needed)

10. In xcode, select device iphone, set code signing identity for build setting
set build identifier for as app ID from info.plist
build and go will install app on iphone


log message for iphone simulator

show in console.app

2009年3月27日 星期五

add photo in iphone simulator

run safari, go to a page with photo, click on photo for 5 seconds, save the photo

2009年3月26日 星期四

iphone error message

[Session started at 2009-03-27 00:21:00 +0800.]

Loading program into debugger…

GNU gdb 6.3.50-20050815 (Apple version gdb-962) (Sat Jul 26 08:14:40 UTC 2008)

Copyright 2004 Free Software Foundation, Inc.

GDB is free software, covered by the GNU General Public License, and you are

welcome to change it and/or distribute copies of it under certain conditions.

Type "show copying" to see the conditions.

There is absolutely no warranty for GDB. Type "show warranty" for details.

This GDB was configured as "i386-apple-darwin".warning: Unable to read symbols for "/System/Library/Frameworks/UIKit.framework/UIKit" (file not found).

warning: Unable to read symbols from "UIKit" (not yet mapped into memory).

warning: Unable to read symbols for "/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics" (file not found).

warning: Unable to read symbols from "CoreGraphics" (not yet mapped into memory).

Program loaded.

sharedlibrary apply-load-rules all


answer: this is usually memory problem, remember to retain & release


use picker


In view controller:
(1) conform protocol: UIPickerViewDelegate, UIPickerViewDataSource
(2) add an outlet for UIPickerView
(3) implement two picker data source method
numberOfComponentInPickerView &
pickerView: numberOfRowsInComponent

In IB:
(1) add picker view to view
(2) connect file's owner's outlet pickerView to pickerView
(3) connect pickerView's outlet dataSource & delegate to file's owner

file's owner

for an xib, there is a file's owner
we can set file's owner's class
this class is the view controller for xib

ex:
create a new xib
create a view controller class A for this xib
In IB
(1) set file's owner as A class
(2) connect file's owner's outlet view to the view icon

2009年3月24日 星期二

tab bar app

1. add a tab ?
in MainWindow.xib, select Tab Bar Controller, use "+" to add tab

2. add a view for tab
(1) create ThirdView.xib
(a) create a view
In IB, file-> new-->cocoa touch template --> view
(b)set simulated metrics for view
ex: status bar , top bar, bottom bar
(c) set file's owner as UIViewController
(d) connect outlet view of file's owner to view window
(e) set nib for tab in IB

3. add a view controller for view
(1) create ThirdViewController.m & .h in xCode
(2) In ThirdView.xib, set file's owner's class identity as ThirdViewController
connect from file's owner's outlet view to view
(3) In MainWindow.xib, set tab
(a)NIB name
(b)class identity: view controller's class
(c)title
(d)image

2009年3月22日 星期日

create multiview app

1. project: window-based app

2. create view controller:
(1)root controller: manage which view to present
(2)content view controller A
(3)content view controller B

3. create nib file
view xib for content view controller

4. create outlet for root controller in app delegate
add root controller's view in applicationDidFinishLaunching
[window addSubview: myRootViewController.view];

5. in root controller's class
(1)add members for content view contrllers
(2)add IBAction to switch content view

6. in IB, create root controller from View Controller
add view to root view controller
add toolbar to view
set the action of button of toolbar as root controller's switch view method

7. in IB, connect app deletgate's outlet to root controller

8. viewDidLoad: the method called when nib is loaded

note: for different iPhone, maybe need to install new profile again



2009年3月21日 星期六

remove app in iphone simulator

delete Library/Application Support/Iphone Simulator from home directory

2009年3月20日 星期五

delegate in iphone

take responsibility for doing something on behalf of another object

ex:
myViewController implements some method of UIWebViewDelegate
it has a member with type UIWebView
then link UIWebView's delegate with myViewController(file's owner) in IB to trigger UIWebViewDelegate method called when something happens

file's owner in interface builder

for view-base app, view controller is file's owner

reason:
MainWindows.xib contain an icon represents myViewController
myViewContrller is created when app launches
when myViewController is created, it will find & load myViewController.xib.
Hence, myViewController is nib file's owner

2009年3月8日 星期日

international call software

冠碼,國碼介紹

動輒13碼以上的國際電話數字及撥號順序常令人錯亂,其實只要記住「冠碼、國碼、區碼、號碼」的順序,便能準確無誤的撥通。
直撥國際電話須先撥所在地「國際冠碼」,再撥受話方「國碼」、「區域號碼」及「電話號碼」,區域號碼前之0不須撥。舉例如下:
1.從國外撥回台灣:該國國際冠碼(詳如下表)+台灣國碼 (886)+區域號碼(去0)+用戶電話號碼。
★如從中國撥回台北市 00+886+2+XXXX-XXXX
★撥台灣行動電話時 00+886+937-XXX-XXX
註:若以手機撥打台灣的電話,只要在國碼886之前以「+」替代該國國際冠碼即可。
2.從台灣撥往國外:台灣國際冠碼(002)+該國國碼+區域號碼(去0)+用戶電話號碼。
★如從台灣撥往中國北京 002+86+10+XXXX-XXXX
★撥中國北京行動電話 002+86+行動電話號碼
註:國際間的行動電話第一碼不一定為0,如是0的話也要去掉。
要注意的是,國碼不會變,但有些國家冠碼卻不只一個,如台灣除熟知的「002」外,還有「009、006」等,差別在於費率。

app:
1. smart dialler
2. calling card
3. edit before call/sms

2009年2月25日 星期三

develop tool

omniobject meter: find memory leak

2009年2月18日 星期三

category

1. add new method to existing class
2. can not add new instance variable to existing class
3. if the method defined in category is the same as existing class,
    it will replace original method of existing class
ex:
add category NumberConvenience to NSString
@interface NSString (NumberConvenience) 
- (NSNumber *) lengthAsNumber; 
@end // NumberConvenience 

@implementation NSString (NumberConvenience) 
- (NSNumber *) lengthAsNumber 
  unsigned int length = [self length]; 
  return ([NSNumber numberWithUnsignedInt: length]); 
} // lengthAsNumber 
@end // NumberConvenience

4. splitting a class's implementation across multiple files or multiple frameworks
ex:
CategoryThing.h
#import  
@interface CategoryThing : NSObject { 
  int thing1; 
  int thing2; 
  int thing3; 
@end // CategoryThing 

@interface CategoryThing (Thing1) 
- (void) setThing1: (int) thing1; 
- (int) thing1; 
@end // CategoryThing (Thing1) 

@interface CategoryThing (Thing2) 
- (void) setThing2: (int) thing2; 
- (int) thing2; 
@end // CategoryThing (Thing2) 

@interface CategoryThing (Thing3) 
- (void) setThing3: (int) thing3; 
- (int) thing3; 
@end // CategoryThing (Thing3) 

categoryThing.m
#import "CategoryThing.h" 
@implementation CategoryThing 
- (NSString *) description 
  NSString *desc; 
  desc = [NSString stringWithFormat: @"%d %d %d", 
           thing1, thing2, thing3]; 
  return (desc); 
} // description 
@end // CategoryThing 

thing1.m
#import "CategoryThing.h" 
@implementation CategoryThing (Thing1) 
- (void) setThing1: (int) t1 
  thing1 = t1; 
} // setThing1 
 
- (int) thing1 
  return (thing1); 
} // thing1 
@end // CategoryThing 

thing2.m & thing3.m are like thing1.m

2009年2月16日 星期一

method calling

method calling:
ex:
[ c setName: @"peter" age: 3];
two parameters, first is @"peter", second is 3
age: is name for second argument

advantage: readability

2009年2月10日 星期二

xcode

tab: complete name

esc: show possible name

ctrl + / :  jump to next argument in the function

move cursor:
ctrl + F: forward
ctrl + B: backward
ctrl + P: to previous line
ctrl + N: to next line
ctrl + A: to beginning of the line
ctrl + E: to end of the line
ctrl + D: delete the char right to the cursor
ctrl + K: delete the chars after the cursor at the same line

cmd + shift + D: show open quickly window to jump to definition

cmd + D: add to bookmark

option + double click:  search in document

2009年2月9日 星期一

memory management

use retain count to do memory management

when retain count becomes 0, the object is destroyed(is sent dealloc message)

when object is created via alloc, new, or copy, the object's retain count is set to 1

use retain to increase retain count

use release to decrease retain count

use retainCount to know object's retain count

retain count in accessor:
ex:
class Boy has an instance variable for book
- (void) setBook: (Book*) newBook
{
[newBook retain];
[book release];
book = newBook;
}
note:
when boy object is deallocated, it will release book object's retain count for retain count it increase in setBook

autorelease:
when object is sent autorelease message, it is put in autorelease pool
when the pool is destroyed, all objects in pool are sent a release message
ex:
NSAutoreleasePool *pool;
pool = [[NSAutoreleasePool alloc] init];
Book *book = [[Book alloc] init];
[book autorelease];
[pool release];
note:
1. for iphone, avoid using autorelease and the functions that give autoreleased object
2. the same object can be autoreleased many times

drain:
the drain method for pool empties out the pool without destroying the pool

rule for reatin count:
1. when getting object from new, alloc, or copy, you must send the object release or autorelease when you are done with it
2. when getting object via other methods, assume it has a retain count of 1 and it has been autoreleased . If you want to hold object for some time, just retain it and release it when you are done
ex:
in an event loop, a pool is created before handling event. And the pool is destroyed after handling event. Hence, the object created during the event loop must retain if you want to keep it
3. if your retain an object, you need to release or autorelease it

garbage collection:
not support iphone
enable gc:
Build -> objective-c garbage collection

dynamic and late binding

you don't have to know the object is class People before calling People's speak method,
the object will find speak method automatically

ex:
Shape *a = [Circle new];
[a draw];
note: Circle's draw method is called

In java, you have to change object's type to People to call People's method
ex:
Shape a = new Circle();
a.draw();  // Shape's draw method is called
(Circle)a.draw();   // Circle's draw method is called

create object ,new, alloc, init, dealloc

new:
ex:
id c = [Circle new];

when creating object with new, two steps are performed :
(1) allocate memory for object
(2) object's init method is called
ex: 
- (id) init
{
self = [super init];
return self;
}

alloc:
initialize all memory to 0
Hence, all instance variable have zero value
pointer to objects are nil
integer variable is 0

dealloc:
- (void) dealloc
 

class:interface, implementation, inheritance, accessor, @property, dot

class declaration:
ex:
@interface Student : NSObject
{
int age;
}
- (void) setAge: (int) age;
- (void) speak;
@end

note:
1.if a method has argument, its name has a colon
2. inheritance:
a. use : , NSObject is super class of Student
b. not support multiple inheritance
3. isa:
instance varabile of NSObject, a pointer to the object's class
ex:
Shape *s = [Circle new];
NSLog(@"isa %@", s->isa);
---> Circle
4: super
call parent class's method definition
ex:
[super speak];

class definition:
@implementation Student
- (void) setAge: (int) a
{
age = a;
}

- (void) speak
{
NSLog(@"speak");
}

@end

note: if parameter uses the same name as instance variable,
use self to distinguish instance variable and parameter
ex:
self->name & name

accessor:
instance variable is protected, can access directly, but usually access from method
ex:
Circle *a = [Circle new];
NSLog(@"name %s", a->name);
id b = [Circle new];
NSLog(@"name %s", ((Circle*)b)->name);
note:
if the variable is with type of parent class,
it will not know instance variable defined in child class
Hence, must use cast
However, call method does not need to cast
the object will find suitable method automatically

name convention for accessor:
getter name conventions:
the same as instance variable name
setter name conventions:
add set before instance variable name
ex:
setAge

new accessor method: @property & @synthesize
create accessor for you
ex:
@interface People {
int age;
}
@property int age;
@end

@implementation People
@synthesize age;
@end

dot:
you can use dot to access instance variable
ex:
peter.age


special keyword in objective-c, id, BOOL, nil, @class

id:
a generic type to refer to any kind of object
ex:
id c = [Circle new];

BOOL:
type for boolean
YES(1) or NO(0)

nil:
1. a zero value
2. a message to nil does not crash, it just do nothing

@class:
when you only need to know the name of class, does not need to know internal structure of class , you can use @class keyword instead of including class header file
ex:
when @class Boy has a instance variable to object dog
use @class Dog
not use #import Dog.h

2009年2月4日 星期三

hello world example, NSLog, NSString

1. new project --> command line utility --> foundation tool

2. Hello.m
#import
int main (int argc, const char *argv[])
{
NSLog (@"Hello, Objective- C!");
return (0);
} // main

3. build and go
click build and go button or com+ R

4. show console
selelct Console from Run or cmd+shift+R


note:
1. import:
like include in C, but guarantees that a header file will be
included only once, no matter how many times the #import
directive is actually seen for
that file.

2. foundation framework:
handle features found in the layers beneath UI, such as
data structure and communication mechanisms
location:
/System/Library/Frameworks/Foundation.framework/Headers/

3. master header file
Each framework has a master header file that includes all the
framework’s individual header files. By using #import on the master header file,
you have access to all the framework’s features

4. NSLog
like printf, but also print date, time , and append newline
%@:
to print object, the object's description method defines what to print
ex:
- (NSString *) description 
    return (@"I am a hero"); 
}

5. NSString
begin with @, such as @"hello"
NSString's advantage:
(1) tell you length
(2)compare with another
(3)convert to interger or floating point