IOS工作筆記1年,收集整理,常用方法


退回輸入鍵盤

  - (BOOL)textFieldShouldReturn:(id)textField{

   [textField  resignFirstResponder];

}

 

CGRect

CGRectframe = CGRectMake (origin.x, origin.y, size.width, size.height);矩形

NSStringFromCGRect(someCG)把CGRect結構轉變爲格式化字符串;

CGRectFromString(aString)由字符串恢復出矩形;

CGRectInset(aRect)創建較小或較大的矩形(中心點相同),+較小  -較大

CGRectIntersectsRect(rect1,rect2) 判斷兩矩形是否交叉,是否重疊

CGRectZero高度和寬度爲零的/位於(0,0)的矩形常量

 

CGPoint& CGSize

CGPointaPoint = CGPointMake(x, y);    

CGSizeaSize = CGSizeMake(width, height);

 

設置透明度

[myViewsetAlpha:value];   (0.0 < value < 1.0)

 

設置背景色 

[myViewsetBackgroundColor:[UIColor redColor]]; 

 (blackColor;darkGrayColor;lightGrayColor;

whiteColor;grayColor;redColor; greenColor; 

blueColor;cyanColor;yellowColor;

magentaColor;orangeColor;purpleColor;

brownColor;clearColor; )

 

自定義顏色

UIColor*newColor = [[UIColor alloc]

 initWithRed:(float)green:(float) blue:(float) alpha:(float)]; 

    0.0~1.0

 

豎屏

320X480

 

橫屏

480X320   

 

狀態欄高 (顯示時間和網絡狀態)

20像素   

 

導航欄、工具欄高(返回)

44像素

 

隱藏狀態欄

[[UIApplicationshareApplication] setStatusBarHidden: YES animated:NO]

 

橫屏

[[UIApplicationshareApplication] 

setStatusBarOrientation:UIInterfaceOrientationLandscapeRight].

 

屏幕變動檢測

orientation== UIInterfaceOrientationLandscapeLeft

 

全屏

window=[[UIWindowalloc] initWithFrame:[UIScreen mainScreen] bounds]; 

 

自動適應父視圖大小:

aView.autoresizingSubviews= YES;

aView.autoresizingMask= (UIViewAutoresizingFlexibleWidth | 

 UIViewAutoresizingFlexibleHeight);

 

 定義按鈕

UIButton*scaleUpButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];

[scaleUpButtonsetTitle:@"放 大" forState:UIControlStateNormal];

scaleUpButton.frame= CGRectMake(40, 420, 100, 40);

[scaleUpButtonaddTarget:self

 action:@selector(scaleUp) 

forControlEvents:UIControlEventTouchUpInside];

 

設置視圖背景圖片

UIImageView*aView;

[aViewsetImage:[UIImage imageNamed:@”name.png”]];

view1.backgroundColor= [UIColor colorWithPatternImage:

[UIImageimageNamed:@"image1.png"]];

 

自定義UISlider的樣式和滑塊

 

我們使用的是UISlider的setMinimumTrackImage,和setMaximumTrackImage方法來定義圖片的,這兩個方法可以設置滑塊左邊和右邊的圖片的,不過如果用的是同一張圖片且寬度和控件寬度基本一致,就不會有變形拉伸的後果,先看代碼,寫在 viewDidLoad中:

   //左右軌的圖片

   UIImage *stetchLeftTrack= [UIImageimageNamed:@"brightness_bar.png"];

   UIImage *stetchRightTrack = [UIImageimageNamed:@"brightness_bar.png"];

   //滑塊圖片

   UIImage *thumbImage = [UIImage imageNamed:@"mark.png"];

   

   UISlider *sliderA=[[UISlider alloc]initWithFrame:CGRectMake(30, 320,257, 7)];

   sliderA.backgroundColor = [UIColor clearColor];

   sliderA.value=1.0;

   sliderA.minimumValue=0.7;

   sliderA.maximumValue=1.0;

   

   [sliderA setMinimumTrackImage:stetchLeftTrackforState:UIControlStateNormal];

   [sliderA setMaximumTrackImage:stetchRightTrackforState:UIControlStateNormal];

   //注意這裏要加UIControlStateHightlighted的狀態,否則當拖動滑塊時滑塊將變成原生的控件

   [sliderA setThumbImage:thumbImage forState:UIControlStateHighlighted];

   [sliderA setThumbImage:thumbImage forState:UIControlStateNormal];

   //滑塊拖動時的事件

   [sliderA addTarget:self action:@selector(sliderValueChanged:)forControlEvents:UIControlEventValueChanged];

   //滑動拖動後的事件

   [sliderA addTarget:self action:@selector(sliderDragUp:)forControlEvents:UIControlEventTouchUpInside];

   

   [self.view addSubview:sliderA]; 

 

爲了大家實驗方便,我附上背景圖brightness_bar.png和滑塊圖mark.png

 HYPERLINK "http://pic002.cnblogs.com/images/2011/162291/2011121611431816.png"http://pic002.cnblogs.com/images/2011/162291/2011121611431816.png

 HYPERLINK "http://pic002.cnblogs.com/images/2011/162291/2011121611432897.png"http://pic002.cnblogs.com/images/2011/162291/2011121611432897.png

 

 -(IBAction)sliderValueChanged:(id)sender{

UISlider*slider = (UISlider *) sender;

NSString*newText = [[NSString alloc] initWithFormat:@”%d”, (int)(slider.value + 0.5f)];

label.text= newText;

}

 

活動表單 

<UIActionSheetDelegate>

 

 -(IBActive) someButtonPressed:(id) sender

{

   UIActionSheet *actionSheet = [[UIActionSheet alloc] 

                  initWithTitle:@”Are you sure?”

                   delegate:self

                  cancelButtonTitle:@”No way!”

                  destructiveButtonTitle:@”Yes, I’m Sure!”

                  otherButtonTitles:nil];

   [actionSheet showInView:self.view];

   [actionSheet release];

}

 

警告視圖 

 <UIAlertViewDelegate>

 

 -(void) actionSheet:(UIActionSheet *)actionSheetdidDismissWithButtonIndex:(NSInteger) buttonIndex

{

    if(buttonIndex != [actionSheet cancelButtonIndex])

    {

         NSString *message = [[NSString alloc]initWithFormat:@”You can          

                  breathe easy,everything went OK.”];

         UIAlertView *alert = [[UIAlertView alloc]   

                             initWithTitle:@”Something was done”

                              message:message

                              delegate:self

                              cancelButtonTitle:@”OK”

                              otherButtonTitles:nil];

         [alert show];

         [alert release];

         [message release];

    }

}

 

動畫效果

-(void)doChange:(id)sender

{

if(view2== nil)

{

[selfloadSec];

}

[UIViewbeginAnimations:nil context:NULL];

[UIViewsetAnimationDuration:1];        

[UIViewsetAnimationTransition:([view1superview]?UIViewAnimationTransitionFlipFromLeft:UIViewAnimationTransitionFlipFromRight)forView:self.viewcache:YES];

  

   if([view1 superview]!= nil)

{

[view1removeFromSuperview];

[self.viewaddSubview:view2];

 

}else {

 

[view2removeFromSuperview];

[self.viewaddSubview:view1];

}

[UIViewcommitAnimations];

}

 

Table View  <UITableViewDateSource>

#pragmamark -

#pragmamark Table View Data Source Methods

//指定分區中的行數,默認爲1

-(NSInteger)tableView:(UITableView *)tableView 

 numberOfRowsInSection:(NSInteger)section

{

return[self.listData count];

}

 

//設置每一行cell顯示的內容

-(UITableViewCell *)tableView:(UITableView *)tableView 

cellForRowAtIndexPath:(NSIndexPath*)indexPath

{

staticNSString *SimpleTableIndentifier = @"SimpleTableIndentifier";

UITableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIndentifier];

if (cell== nil) {

cell =[[[UITableViewCell alloc] 

initWithStyle:UITableViewCellStyleSubtitle 

reuseIdentifier:SimpleTableIndentifier] 

autorelease];

}

    UIImage *image = [UIImage imageNamed:@"13.gif"];

cell.imageView.image= image;

    

NSUIntegerrow = [indexPath row];

cell.textLabel.text= [listData objectAtIndex:row];

    cell.textLabel.font = [UIFont boldSystemFontOfSize:20];

 

    if(row < 5)

cell.detailTextLabel.text= @"Best friends";

else 

   cell.detailTextLabel.text = @"friends";

returncell;

}

 

圖像、文本標籤和詳細文本標籤

 

圖像:如果設置圖像,則它顯示在文本的左側;文本標籤:這是單元的主要文本(UITableViewCellStyleDefault 只顯示文本標籤);詳細文本標籤:這是單元的輔助文本,通常用作解釋性說明或標籤

 

UITableViewCellStyleSubtitle

UITableViewCellStyleDefault

UITableViewCellStyleValue1

UITableViewCellStyleValue2

 

<UITableViewDelegate>

#pragmamark -

#pragmamark Table View Delegate Methods

//把每一行縮進級別設置爲其行號

-(NSInteger)tableView:(UITableView *)tableViewindentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath

{

NSUIntegerrow = [indexPath row];

returnrow;

}

//獲取傳遞過來的indexPath值

-(NSIndexPath *)tableView:(UITableView *)tableViewwillSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

NSUIntegerrow = [indexPath row];

if (row ==0) 

returnnil;

returnindexPath;

}

 

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath

{

NSUIntegerrow = [indexPath row];

NSString*rowValue = [listData objectAtIndex:row];

NSString*message = [[NSString alloc] initWithFormat:@"You selected%@",rowValue];

UIAlertView*alert = [[UIAlertView alloc] initWithTitle:@"Row Selected"

message:message

   delegate:nil

 cancelButtonTitle:@"Yes, I did!"

 otherButtonTitles:nil];

[alertshow];

[alertrelease];

[messagerelease];

[tableViewdeselectRowAtIndexPath:indexPath animated:YES];

}

 

//設置行的高度

-(CGFloat)tableView:(UITableView *)tableViewheightForRowAtIndexPath:(NSIndexPath *)indexPath

{

return 40;

}

 

NavigationController推出push 推出pop

[self.navigationControllerpushViewController:_detailController animated:YES];

[self.navigationControllerpopViewControllerAnimated:YES];

 

Debug:

NSLog(@"%s%d", __FUNCTION__, __LINE__);

 

點擊textField外的地方回收鍵盤

 

先定義一個UIControl類型的對象,在上面可以添加觸發事件,令SEL實踐爲回收鍵盤的方法,最後將UIControl的實例加到當前View上。

UIControl*m_control = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];

[m_controladdTarget:self action:@selector(keyboardReturn) 

forControlEvents:UIControlEventTouchUpInside];

[self.viewaddSubview:m_control];

 

- (void)keyboardReturn

{

[aTextFieldresignFirstResponder];

}

 

鍵盤覆蓋輸入框

當鍵盤調出時將輸入框覆蓋時,可以用下方法:

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField

{

[self.viewsetFrame:CGRectMake(0, -100, 320, 480) ];

returnYES;

}

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField

{

 [self.view setFrame:CGRectMake(0, 0, 320, 480)];

returnYES;

}

當準備輸入時,將視圖的位置上調100,這樣鍵盤就不能覆蓋到輸入框。

 

當依賴注入方法不好使時,可以在AppDelegate內申明一個全局的控制器實例_anotherViewController,在另一個需要使用_anotherViewController的地方定義以下委託方法,使用共享的UIApplication實例來獲取該委託的引用

SomeAppDelegate*appDelegate = (SomeAppDelegate *)[[UIApplication sharedApplication] delegate];

_anotherViewController= appDelegate._anotherViewController; 

 

UIViewController內建Table View

 

純代碼在UIViewController控制器內建TableView

@interfaceRootViewController : UIViewController <UITableViewDelegate,UITableViewDataSource> {

NSArray*timeZoneNames;

}

@property(nonatomic,retain) NSArray *timeZoneNames;

@end

 

(void)loadView

{

UITableView*tableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen]applicationFrame]] style: UITableViewStylePlain];

tableView.autoresizingMask= (UIViewAutoresizingFlexibleHeight | UIViewAutoresizingWidth);

tableView.delegate= self;

tableView.dataSource= self;

[tableViewreloadData];

 

self.view= tableView;

[tableViewrelease];

}

 

 

將plist文件中的數據賦給數組

NSString*thePath = [[NSBundle mainBundle] pathForResource:@"States"ofType:@"plist"];

NSArray*array = [NSArray arrayWithContentsOfFile:thePath];

 

UITouch

手指的觸摸範圍:64X64 

 

#pragmamark -

#pragmamark Touch Events

 

-(void)touchesBegan:(NSSet *) touches withEvent:(UIEvent *) event {

originFrame= bookCover.frame;

NSLog(@"%s%d", __FUNCTION__,__LINE__);

 

if([touches count] == 2) 

{

NSArray*twoTouches = [touches allObjects];

UITouch*firstTouch = [twoTouches objectAtIndex:0];

UITouch*secondTouch = [twoTouches objectAtIndex:1];

CGPointfirstPoint = [firstTouch locationInView:bookCover];

CGPointsecondPoint = [secondTouch locationInView:bookCover];

 

CGFloatdeltaX = secondPoint.x - firstPoint.x;

CGFloatdeltaY = secondPoint.y - firstPoint.y; 

initialDistance= sqrt(deltaX * deltaX + deltaY * deltaY ); 

frameX =bookCover.frame.origin.x;

frameY =bookCover.frame.origin.y;

frameW =bookCover.frame.size.width;

frameH =bookCover.frame.size.height;

NSLog(@"%s%d", __FUNCTION__,__LINE__);

}

}

 

-(void)touchesMoved:(NSSet *) touches withEvent:(UIEvent *) event { 

 

if([touchescount] == 2)

NSLog(@"%s%d", __FUNCTION__,__LINE__);

 

NSArray*twoTouches = [touches allObjects];

UITouch*firstTouch = [twoTouches objectAtIndex:0];

UITouch*secondTouch = [twoTouches objectAtIndex:1];

 

CGPointfirstPoint = [firstTouch locationInView:bookCover];

CGPointsecondPoint = [secondTouch locationInView:bookCover];

 

CGFloatdeltaX = secondPoint.x - firstPoint.x;

CGFloatdeltaY = secondPoint.y - firstPoint.y; 

CGFloatcurrentDistance = sqrt(deltaX * deltaX + deltaY * deltaY ); 

 

if(initialDistance == 0) {

initialDistance= currentDistance;

}

else if(currentDistance != initialDistance)

{

CGFloatchangedDistance = currentDistance - initialDistance;

NSLog(@"changedDistance= %f",changedDistance);

[bookCoversetFrame:CGRectMake(frameX - changedDistance / 2, 

frameY -(changedDistance * frameH) / (2 * frameW),

frameW +changedDistance, 

frameH +(changedDistance * frameH) / frameW)];

}

}

}

 

-(void)touchesEnded:(NSSet *) touches withEvent:(UIEvent *) event {

UITouch*touch = [touches anyObject];

 

UITouch雙擊圖片變大/還原

if ([touchtapCount] == 2) 

{

NSLog(@"%s%d", __FUNCTION__,__LINE__);

 

if (!flag){

[bookCoversetFrame:CGRectMake(bookCover.frame.origin.x - bookCover.frame.size.width / 2,

bookCover.frame.origin.y- bookCover.frame.size.height / 2,

2 *bookCover.frame.size.width, 

2 *bookCover.frame.size.height)];

flag =YES;

}

else {

[bookCoversetFrame:CGRectMake(bookCover.frame.origin.x + bookCover.frame.size.width / 4,bookCover.frame.origin.y + bookCover.frame.size.height / 4,

bookCover.frame.size.width/ 2, bookCover.frame.size.height / 2)]; 

flag = NO;

}

}

 

Getthe Location of Touches

(CGPoint)locationInView:(UIView*)view

(CGPoint)previousLocationInView:(UIView*)view

viewwindow

 

GettingTouch Attributes

tapCount(readonly) timestamp(read only) phase(read only)

 

Getting aTouch Object's Gesture Recognizers

gestureRecognizers 

 

TouchPhase

UITouchPhaseBegan

UITouchPhaseMoved

UITouchPhaseStationary

UITouchPhaseEnded

UITouchPhaseCancelled

 

從Plist裏讀內容

NSString*plistPath = [[NSBundle mainBundle] pathForResource:@"book"ofType:@"plist"];

NSDictionary*dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];

NSString*book = [dictionary objectForKey:bookTitle];

[textViewsetText:book];

 

(void)initialize {

NSUserDefaults= [NSUserDefaults standardUserDefaults];

NSDictionary*appDefaults = [NSDictionary dictionaryWithObject:@"YES"forKey:@"DeleteBackup"];

[defaultsregisterDefaults:appDefaults];

}

 

To get avalue of a default, use the valueForKey: method:

[[theDefaultsControllervalues] valueForKey:@"userName"];

To set avalue for a default, use setValue:forKey:

[[theDefaultsControllervalues] setValue:newUserName forKey:@"userName"];

 

[[NSUserDefaultsstandardUserDefaults] setValue:aVale forKey:aKey];

[[NSUserDefaultsstandardUserDefaults] valueForKey:aKey];

 

獲取Documents目錄

NSArray*paths = NSSearchPathForDictionariesInDomains(NSDocumentDirectory, 

NSUserDomainMask,YES);

NSString*documentsDirectory = [paths objectAtIndex:0];

NSString*filename = [documentsDirectory 

stringByAppendingPathComponent:@"theFile.txt"];

 

獲取tmp目錄

NSString*tempPath = NSTemporaryDirectory();

NSString*tempFile = [tempPathstringByAppendingPathComponent:@"tempFile.txt"];

 

[[NSUserDefaultsstandardUserDefaults] setObject:data forKey:@"someKey"];

[[NSUserDefaultsstandardUserDefaults] objectForKey:aKey];

 

自定義NavigationBar

navigationBar= [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];

[navigationBarsetBarStyle:UIBarStyleBlackOpaque];

 

myNavigationItem= [[UINavigationItem alloc] initWithTitle:@"Setting"];

[navigationBarsetItems:[NSArray arrayWithObject:myNavigationItem]];

[self.viewaddSubview:navigationBar];

 

backButton= [[UIBarButtonItem alloc] initWithTitle:@"Back"style:UIBarButtonItemStylePlain target:self action:@selector(back)];

myNavigationItem.leftBarButtonItem= backButton;

 

 

利用Safari打開一個鏈接

NSURL *url= [NSURL URLWithString:@"http://www.cnblogs.com/tracy-e/"];

[[UIApplicationsharedApplication] openURL:url];

 

利用UIWebView顯示pdf文件、網頁。。。

webView =[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];

[webViewsetDelegate:self];

[webViewsetScalesPageToFit:YES];

[webViewsetAutoresizingMask:UIViewAutoresizingFlexibleWidth |UIViewAutoresizingFlexibleHeight];

[webViewsetAllowsInlineMediaPlayback:YES];

[self.viewaddSubview:webView];

NSString*pdfPath = [[NSBundle mainBundle] pathForResource:@"ojc"ofType:@"pdf"]; 

NSURL *url= [NSURL fileURLWithPath:pdfPath]; 

NSURLRequest*request = [NSURLRequest requestWithURL:url 

cachePolicy:NSURLRequestUseProtocolCachePolicy

timeoutInterval:5];

[webViewloadRequest:request];

 

 

[myWebViewloadRequest:[NSURLRequest requestWithURL:[NSURL 

                     URLWithString: @"http://www.cnblogs.com/tracy-e/"]]];

 

NSString*errorString = [NSStringstringWithFormat:@"<html><center><font size= 

+5 color='red'>An ErrorOccurred:<br>%@</fone></center></html>",error];

[myWebViewloadHTMLString:errorString baseURL:nil];

 

//Stoppinga load request when the view is to disappear

-(void)viewWillDisappear:(BOOL)animate{

if([myWebView loading]){

[myWebViewstopLoading];

}

myWebView.delegate= nil;

[UIApplicationshareApplication].networkActivityIndicatorVisible = NO;

}

 

漢字轉碼

NSString*oriString = @"\u67aa\u738b";

NSString*escapedString = [oriString 

stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

 

 

Checkingfor background support on earlier versions of iOS

UIDevice*device = [UIDevice currentDevice];

BOOLbackgroundSupported = NO;

if([device respondsToSelector:@selector(isMultitaskingSupported)]){

backgroundSupported= device.multitaskingSupported;

}

 

Being aResponsible,Multitasking-Aware Application 

# Do notmake any OpenGL ES calls from your code.

# Cancelany Bonjour-related services before being suspended.

# Beprepared to handle connection failures in your network-based sockets.

# Saveyour application state before moving to the background.

# Releaseany unneeded memory when moving to the background.

# Stopusing shared system resources before being suspended.

# Avoidupdating your windows and views.

# Respondto connect and disconnect notification for external accessories.

# Clean upresource for active alerts when moving to the background.

# Removesensitive information from views before moving to the background.

# Dominimal work while running in the background.

 

Handingthe Keyboard notifications

//Callthis method somewhere in your view controller setup code

- (void)registerForKeyboardNotifications{

 

[[NSNotificationCenterdefaultCenter] addObserver:self

selector:@selector(keyboardWasShown:)

name:UIKeyboardDidShowNotification 

object:nil];

[[NSNotificationCenterdefaultCenter] addObserver:self

selector:@selector(keyboardWasHidden:)

name:UIKeyboardDidHideNotification

object:nil];

 

}

 

//Calledwhen the UIKeyboardDidShowNotification is sent

-(void)keyboardWasShown:(NSNotification *) aNotification{

if(keyboardShown)

return;

NSDictionary*info = [aNotification userInfo];

 

//get thesize of the keyboard. 

NSValue*aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];

CGSizekeyboardSize = [aValue CGRectValue].size;

 

//Resizethe scroll view 

CGRectviewFrame = [scrollView frame];

viewFrame.size.height-= keyboardSize.height;

 

//Scrollthe active text field into view

CGRecttextFieldRect = [activeField frame];

[scrollViewscrollRectToVisible:textFieldRect animated:YES];

 

keyboardShown= YES; 

}

 

//Calledwhen the UIKeyboardDidHideNotification is sent

-(void)keyboardWasHidden:(NSNotification *) aNotification{

NSDictionary*info = [aNotification userInfo];

 

//Get thesize of the keyboard.

NSValue*aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];

CGSizekeyboardSize = [aValue CGRectValue].size;

 

//Resetthe height of the scroll view to its original value

CGRectviewFrame = [scrollView Frame];

viewFrame.size.height+= keyboardSize.height;

scrollView.frame= viewFrame;

 

keyboardShown= NO;

}

 

點擊鍵盤的next按鈕,在不同的textField之間換行

//首先給不同的textField賦不同的且相鄰的tag值

-(BOOL)textFieldShouldReturn:(UITextField *)textField

{

if([textField returnKeyType] != UIReturnKeyDone)

NSIntegernextTag = [textField tag] + 1;

UIView*nextTextField = [[self tableView] viewWithTag:nextTag];

[nextTextFieldbecomeFirstResponder];

}

else {

[textFieldresignFirstResponder];

}

returnYES;

 

Configuringa date formatter 

-(void)viewDidLoad {

[superviewDidLoad];

dateFormatter= [[NSDateFormatter alloc] init];

[dateFormattersetGeneratesCalendarDates:YES];

[dateFormattersetLocale:[NSLocale currentLocale]];

[dateFormattersetCalendar:[NSCalendar autoupdatingCurrentCalendar]];

[dateFormattersetTimeZone:[NSTimeZone defaultTimeZone]];

[dateFormattersetDateStyle:NSDateFormatterShortStyle];

DOB.placeholder= [NSString stringWithFormat:@"Example: %@",[dateFormatterstringFromDate:[NSDate date]]];

}

 

-(void)textFieldDidEndEditing:(UITextField *)textField{

[textFieldresignFirstResponder];

if([textField.text isEqualToString:@""])

return;

switch(textField.tag){

caseDOBField:

NSDate*theDate = [dateFormatter dateFromString:textField.text];

if(theDate)

[inputDatesetObject:theDate forKey:MyAppPersonDOBKey];

break;

default:

break;

}

}

 

 tableView的cell高度

 

tableView的cell高度除了在delegate中指定外,還可以在任意位置以[tableViewsetRowHeight:44]的方式指定

 

[[selfnavigationItem] setLeftBarButtonItem:[self editButtonItem]];

 

-(void)setEditing:(BOOL)editing animated:(BOOL)animated{

[supersetEditing:editing animated:animated];

if(editing){

...... 

}

else{

......

}

 

One addeda subview to a view, release the subview to avoid the extra retain count of it,Because when you insert a view as a subview using addSubview:, the subview isretained by its superview. When you remove the subview from its superview usingthe removeFromSuperview: method, subview is autoreleased.

 

爲UINavigationBar設置背景圖片

在iPhone開發中, 有時候我們想給導航條添加背景圖片, 實現多樣化的導航條效果, 用其他方法往往無法達到理想的效果, 經過網上搜索及多次實驗, 確定如下最佳實現方案:

爲UINavigatonBar增加如下Category(類別:提供一種爲某個類添加方法而又不必編寫子類的途徑,類別只能添加成員函數,不能添加數據成員):

 

@implementation UINavigationBar (CustomImage)  

- (void)drawRect:(CGRect)rect {  

    UIImage *image = [UIImage imageNamed: @"NavigationBar.png"];  

    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];  

}  

@end  

 

例如, 在我的項目中, 添加如下代碼:

/////////////////////////////////////////////////////////  

/* input: The image and a tag to later identify the view */  

@implementation UINavigationBar (CustomImage)  

- (void)drawRect:(CGRect)rect {  

    UIImage *image = [UIImage imageNamed: @"title_bg.png"];  

    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];  

}  

@end  

/////////////////////////////////////////////////////////  

@implementation FriendsPageViewController  

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.  

- (void)viewDidLoad {     

    self.navigationBar.tintColor = [UIColor purpleColor];  

      

    [self initWithRootViewController:[[RegPageViewController alloc] init]];  

    [super viewDidLoad];  

}  

......  

實現的效果如下圖:

 INCLUDEPICTURE "http://www.cocoachina.com/cms/uploads/allimg/100618/8_100618152649_1.png"\* MERGEFORMATINET 

 

轉載,原文地址 http://blog.csdn.net/wave_1102/archive/2009/11/04/4768212.aspx

 

 HYPERLINK"http://www.cnblogs.com/nasa/archive/2010/11/08/UINavigationBar-bg.html"UINavigationBar添加自定義背景

 

@implementationUINavigationBar (UINavigationBarCategory)  

 

-(void)drawRect:(CGRect)rect {  

   //顏色填充  

// UIColor *color = [UIColor redColor];  

// CGContextRef context = UIGraphicsGetCurrentContext();  

// CGContextSetFillColor(context, CGColorGetComponents( [color CGColor]));  

// CGContextFillRect(context, rect);  

// self.tintColor = color;  

   //圖片填充  

UIColor*color = [UIColor colorWithRed:46.0f/255.0f 

green:87.0f/255.0fblue:29.0f/255.0f alpha:1.0f];

 

   UIImage *img    = [UIImage imageNamed: @"bg.png"]; 

   [img drawInRect:CGRectMake(0, 0, self.frame.size.width,self.frame.size.height)];  

 

   self.tintColor = color;  

}  

 

@end

 

加載圖片要及時release

 

你還在使用myImage= [UIImage imageNamed:@"icon.png"]; 嗎? 

 

如題,是不是大家爲了方便都這樣加載圖片啊

 

myImage =[UIImage imageNamed:@"icon.png"];

 

那麼小心了

 

這種方法在一些圖片很少,或者圖片很小的程序裏是ok的。

 

但是,在大量加載圖片的程序裏,請千萬不要這樣做。

 

爲什麼呢 ???????

 

這種方法在application bundle的頂層文件夾尋找由供應的名字的圖象。 如果找到圖片,裝載到iPhone系統緩存圖象。那意味圖片是(理論上)放在內存裏作爲cache的。

 

試想你圖片多了,是什麼後果? 

 

圖片cache極有可能不會響應 memorywarnings and release its objects

 

所以,用圖片的時候一定要小心的alloc和release。

 

推薦使用 NSString *path = [[NSBundle mainBundle]pathForResource:@"icon" ofType:@"png"];

 

myImage =[UIImage imageWithContentsOfFile:path];

 

// Todouse of myImage

 

[myImagerelease];

 

From: HYPERLINK "http://www.cocoachina.com/bbs/simple/?t27420.html"http://www.cocoachina.com/bbs/simple/?t27420.html 

 

uiwebview打開doc,pdf文件

UIWebView*webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 55, 320, 300)];

   webView.delegate = self;

   webView.multipleTouchEnabled = YES;

   webView.scalesPageToFit = YES;

 

   NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);

   NSString *documentsDirectory = [paths objectAtIndex:0];

   NSString *docPath = [documentsDirectorystringByAppendingString:@"/doc2003_1.doc"];   NSLog(@"#######%@",docPath);

   

   NSURL *url = [NSURL fileURLWithPath:docPath];

   NSURLRequest *request = [NSURLRequest requestWithURL:url];

   [webView loadRequest:request];

   

   [self.view addSubview:webView];

[webViewrelease];

 

From:HYPERLINK "http://blog.csdn.net/dadalan/archive/2010/10/22/5959301.aspx"http://blog.csdn.net/dadalan/archive/2010/10/22/5959301.aspx 

 

iPhone遊戲中既播放背景音樂又播放特效聲音的辦法

 

有時候在 iPhone 遊戲中,既要播放背景音樂,同時又要播放比如槍的開火音效。此時您可以試試以下方法

 

   NSString *musicFilePath = [[NSBundle mainBundle]pathForResource:fileName ofType:@"wav"];       //創建音樂文件路徑

   NSURL *musicURL = [[NSURL alloc] initFileURLWithPath:musicFilePath]; 

   AVAudioPlayer* musicPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:musicURL error:nil];

   [musicURL release];

   [musicPlayer prepareToPlay];

   //[musicPlayer setVolume:1];            //設置音量大小

   //musicPlayer .numberOfLoops = -1;//設置音樂播放次數 -1爲一直循環

 

要導入框架 AVFoundation.framework,頭文件中#import <AVFoundation/AVFoundation.h>;做成類的話則更方便。

 

From: HYPERLINK "http://blog.csdn.net/dadalan/archive/2010/10/19/5950493.aspx"http://blog.csdn.net/dadalan/archive/2010/10/19/5950493.aspx 

 

NSNotificationCenter用於增加回調函數

[[NSNotificationCenterdefaultCenter] addObserver:self selector:@selector(_willBecomeActive)name:UIApplicationDidBecomeActiveNotification object:nil];

 

UINavigationBar 背景Hack

LOGO_320×44.png圖片顯示在背景上,

 

@implementationUINavigationBar (UINavigationBarCategory)

-(void)drawRect:(CGRect)rect {

//加入旋轉座標系代碼

   // Drawing code

UIImage*navBarImage = [UIImage imageNamed:@"LOGO_320×44.png"];

CGContextRefcontext = UIGraphicsGetCurrentContext();

CGContextTranslateCTM(context,0.0, self.frame.size.height);

CGContextScaleCTM(context,1.0, -1.0);

CGPointcenter=self.center;

 

CGImageRefcgImage= CGImageCreateWithImageInRect(navBarImage.CGImage, CGRectMake(0, 0, 1,44));

CGContextDrawImage(context,CGRectMake(center.x-160-80, 0, 80, self.frame.size.height), cgImage);

CGContextDrawImage(context,CGRectMake(center.x-160, 0, 320, self.frame.size.height), navBarImage.CGImage);

CGContextDrawImage(context,CGRectMake(center.x+160, 0, 80, self.frame.size.height), cgImage);

}

@end

 

old code

CGContextDrawImage(context,CGRectMake(0, 0, self.frame.size.width, self.frame.size.height),navBarImage.CGImage);

 

hack過logo 不再拉伸

 INCLUDEPICTURE"http://iphone.ipsw.info/assets_c/2010/06/nav_bar-thumb-320x172-47.png"\* MERGEFORMATINET 

From: HYPERLINK "http://blog.163.com/fengyi1103@126/blog/static/13835627420106279102671/"http://blog.163.com/fengyi1103@126/blog/static/13835627420106279102671/ 

 

清除電話號碼中的其他符號(源碼)

 

最近從通訊錄讀取電話號碼,讀出得號碼如:134-1814-****。

而我需要的爲11位純數字,一直找方法解決此問題,今天終於找到了。。

分享一下……

 

代碼如下:

 

NSString*originalString = @"(123) 123123 abc";

NSMutableString*strippedString = [NSMutableString 

       stringWithCapacity:originalString.length];

 

NSScanner*scanner = [NSScanner scannerWithString:originalString];

NSCharacterSet*numbers = [NSCharacterSet 

      characterSetWithCharactersInString:@"0123456789"];

 

while([scanner isAtEnd] == NO) {

 NSString *buffer;

  if([scanner scanCharactersFromSet:numbers intoString:&buffer]) {

   [strippedString appendString:buffer];

  }

  //--------- Add the following to get out of endless loop

 else {

    [scanner setScanLocation:([scanner scanLocation] + 1)];

  }   

  //--------- End of addition

}

 

NSLog(@"%@",strippedString); // "123123123"

 

From: HYPERLINK "http://stackoverflow.com/questions/1129521/remove-all-but-numbers-from-nsstring"http://stackoverflow.com/questions/1129521/remove-all-but-numbers-from-nsstring 

 

 

正則判斷:字符串只包含字母和數字

 

NSString*mystring = @"Letter1234";

NSString*regex = @"[a-z][A-Z][0-9]";

 

NSPredicate*predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];

 

if([predicate evaluateWithObject:mystring] == YES) {

    //implement

}

 

 

一行代碼設置UITableViewCell 與導航條間距

 

UITableView的 cell 默認出現在 uitableview 的第一行,如果你想自定義 UITableViewCell 與導航條間距的話,可以使用下面這行代碼

 

tableview.tableHeaderView= [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)]autorelease];

 

From: HYPERLINK "http://blog.163.com/fengyi1103@126/blog/static/1383562742010101611107492/"http://blog.163.com/fengyi1103@126/blog/static/1383562742010101611107492/ 

 

 

修改 UITableview 滾動條顏色的方法

 

   UITableview 的滾動條默認顏色是黑色的,如果 UItableview 背景也是深顏色,則滾動條會變的很不明顯。您可以用下面這行代碼來改變滾動條的顏色

 

self.tableView.indicatorStyle=UIScrollViewIndicatorStyleWhite;

 

當然,最後的 “White” 也可以換成其它顏色。

 

 

下文件之前獲取到文件大小的代碼

 

下面這段代碼,能實現在下載文件之前獲得文件大小,應用在軟件裏,能在很大程度上改善用戶體驗

 

[m_pASIHTTPRequestsetDidReceiveResponseHeadersSelector:@selector(didReceiveResponseHeaders:)];

 

-(void)didReceiveResponseHeaders:(ASIHTTPRequest *)request

{

   NSLog(@"didReceiveResponseHeaders%@",[m_request.responseHeaders valueForKey:@"Content-Length"]);

 

網絡編程總結 iphone

 

一:確認網絡環境3G/WIFI

 

   1. 添加源文件和framework

   

   開發Web等網絡應用程序的時候,需要確認網絡環境,連接情況等信息。如果沒有處理它們,是不會通過Apple的審(我們的)查的。

   Apple 的 例程 Reachability 中介紹了取得/檢測網絡狀態的方法。要在應用程序程序中使用Reachability,首先要完成如下兩部:

   

   1.1. 添加源文件:

   在你的程序中使用 Reachability 只須將該例程中的Reachability.h 和 Reachability.m 拷貝到你的工程中。如下圖:

 

   

   

   1.2.添加framework:

   將SystemConfiguration.framework 添加進工程。如下圖:

   

   

   2. 網絡狀態

   

   Reachability.h中定義了三種網絡狀態:

   typedef enum {

       NotReachable = 0,           //無連接

       ReachableViaWiFi,           //使用3G/GPRS網絡

       ReachableViaWWAN           //使用WiFi網絡

   } NetworkStatus;

   

   因此可以這樣檢查網絡狀態:

 

   Reachability *r = [ReachabilityreachabilityWithHostName:@“www.apple.com”];

   switch ([r currentReachabilityStatus]) {

           case NotReachable:

                   // 沒有網絡連接

                   break;

           case ReachableViaWWAN:

                   // 使用3G網絡

                   break;

           case ReachableViaWiFi:

                   // 使用WiFi網絡

                   break;

   }

   

   3.檢查當前網絡環境

   程序啓動時,如果想檢測可用的網絡環境,可以像這樣

   // 是否wifi

   + (BOOL) IsEnableWIFI {

       return ([[Reachability reachabilityForLocalWiFi]currentReachabilityStatus] != NotReachable);

   }

 

   // 是否3G

   + (BOOL) IsEnable3G {

       return ([[Reachability reachabilityForInternetConnection]currentReachabilityStatus] != NotReachable);

   }

   例子:

   - (void)viewWillAppear:(BOOL)animated {    

   if (([ReachabilityreachabilityForInternetConnection].currentReachabilityStatus == NotReachable)&& 

           ([ReachabilityreachabilityForLocalWiFi].currentReachabilityStatus == NotReachable)) {

           self.navigationItem.hidesBackButton = YES;

           [self.navigationItemsetLeftBarButtonItem:nil animated:NO];

       }

   }

 

   4. 鏈接狀態的實時通知

   網絡連接狀態的實時檢查,通知在網絡應用中也是十分必要的。接續狀態發生變化時,需要及時地通知用戶:

   

   Reachability 1.5版本

   // My.AppDelegate.h

   #import "Reachability.h"

 

   @interface MyAppDelegate : NSObject <UIApplicationDelegate> {

       NetworkStatus remoteHostStatus;

   }

 

   @property NetworkStatus remoteHostStatus;

 

   @end

 

   // My.AppDelegate.m

   #import "MyAppDelegate.h"

 

   @implementation MyAppDelegate

   @synthesize remoteHostStatus;

 

   // 更新網絡狀態

   - (void)updateStatus {

       self.remoteHostStatus = [[Reachability sharedReachability]remoteHostStatus];

   }

 

   // 通知網絡狀態

   - (void)reachabilityChanged:(NSNotification *)note {

       [self updateStatus];

       if (self.remoteHostStatus == NotReachable) {

           UIAlertView *alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"AppName", nil)

                       message:NSLocalizedString (@"NotReachable", nil)

                      delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];

           [alert show];

           [alert release];

       }

   }

 

   // 程序啓動器,啓動網絡監視

   - (void)applicationDidFinishLaunching:(UIApplication *)application {

   

       // 設置網絡檢測的站點

       [[Reachability sharedReachability]setHostName:@"www.apple.com"];

       [[Reachability sharedReachability]setNetworkStatusNotificationsEnabled:YES];

       // 設置網絡狀態變化時的通知函數

       [[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(reachabilityChanged:)

                                              name:@"kNetworkReachabilityChangedNotification" object:nil];

       [self updateStatus];

   }

 

   - (void)dealloc {

       // 刪除通知對象

       [[NSNotificationCenter defaultCenter]removeObserver:self];

       [window release];

       [super dealloc];

   } 

   

   Reachability 2.0版本

   

 

   // MyAppDelegate.h

   @class Reachability;

 

       @interface MyAppDelegate : NSObject<UIApplicationDelegate> {

           Reachability  *hostReach;

       }

 

   @end

 

   // MyAppDelegate.m

   - (void)reachabilityChanged:(NSNotification *)note {

       Reachability* curReach = [note object];

       NSParameterAssert([curReach isKindOfClass: [Reachabilityclass]]);

       NetworkStatus status = [curReachcurrentReachabilityStatus];

   

       if (status == NotReachable) {

           UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"AppName""

                            message:@"NotReachable"

                            delegate:nil

                            cancelButtonTitle:@"YES" otherButtonTitles:nil];

                            [alert show];

                            [alert release];

       }

   }

                            

   - (void)applicationDidFinishLaunching:(UIApplication *)application {

       // ...

                 

       // 監測網絡情況

       [[NSNotificationCenter defaultCenter] addObserver:self

                            selector:@selector(reachabilityChanged:)

                            name: kReachabilityChangedNotification

                            object: nil];

       hostReach = [[ReachabilityreachabilityWithHostName:@"www.google.com"] retain];

       hostReach startNotifer];

       // ...

   }

 

 

二:使用NSConnection下載數據

   

   1.創建NSConnection對象,設置委託對象

   

   NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:[NSURL URLWithString:[self urlString]]];

   [NSURLConnection connectionWithRequest:request delegate:self];

   

   2. NSURLConnection delegate委託方法

       - (void)connection:(NSURLConnection *)connectiondidReceiveResponse:(NSURLResponse *)response;  

       - (void)connection:(NSURLConnection *)connectiondidFailWithError:(NSError *)error;  

       - (void)connection:(NSURLConnection *)connectiondidReceiveData:(NSData *)data;  

       - (void)connectionDidFinishLoading:(NSURLConnection*)connection;  

 

   3. 實現委託方法

   - (void)connection:(NSURLConnection *)connectiondidReceiveResponse:(NSURLResponse *)response {

       // store data

       [self.receivedData setLength:0];           //通常在這裏先清空接受數據的緩存

   }

   

   - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {

          /* appends the new data to the received data */

       [self.receivedData appendData:data];       //可能多次收到數據,把新的數據添加在現有數據最後

   }

 

   - (void)connection:(NSURLConnection *)connectiondidFailWithError:(NSError *)error {

       // 錯誤處理

   }

 

   - (void)connectionDidFinishLoading:(NSURLConnection *)connection {

       // disconnect

       [UIApplicationsharedApplication].networkActivityIndicatorVisible = NO;   

       NSString *returnString = [[NSString alloc]initWithData:self.receivedData encoding:NSUTF8StringEncoding];

       NSLog(returnString);

       [self urlLoaded:[self urlString] data:self.receivedData];

       firstTimeDownloaded = YES;

   }

 

三:使用NSXMLParser解析xml文件

 

   1. 設置委託對象,開始解析

   NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];   //或者也可以使用initWithContentsOfURL直接下載文件,但是有一個原因不這麼做:

   // It's also possible to have NSXMLParser download the data, by passingit a URL, but this is not desirable

   // because it gives less control over the network, particularly inresponding to connection errors.

   [parser setDelegate:self];

   [parser parse];

 

   2. 常用的委託方法

   - (void)parser:(NSXMLParser *)parser didStartElement:(NSString*)elementName 

                              namespaceURI:(NSString *)namespaceURI

                              qualifiedName:(NSString *)qName 

                              attributes:(NSDictionary *)attributeDict;

   - (void)parser:(NSXMLParser *)parser didEndElement:(NSString*)elementName 

                              namespaceURI:(NSString *)namespaceURI 

                              qualifiedName:(NSString *)qName;

   - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string;

   - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError*)parseError;

 

   static NSString *feedURLString = @" HYPERLINK "http://www.yifeiyang.net/test/test.xml"http://www.yifeiyang.net/test/test.xml";

 

   3.  應用舉例

   - (void)parseXMLFileAtURL:(NSURL *)URL parseError:(NSError **)error

   {

       NSXMLParser *parser = [[NSXMLParser alloc]initWithContentsOfURL:URL];

       [parser setDelegate:self];

       [parser setShouldProcessNamespaces:NO];

       [parser setShouldReportNamespacePrefixes:NO];

       [parser setShouldResolveExternalEntities:NO];

       [parser parse];

       NSError *parseError = [parser parserError];

       if (parseError && error) {

           *error = parseError;

       }

       [parser release];

   }

 

   - (void)parser:(NSXMLParser *)parser didStartElement:(NSString*)elementName namespaceURI:(NSString *)namespaceURI 

                                     qualifiedName:(NSString*)qName attributes:(NSDictionary *)attributeDict{

       // 元素開始句柄

       if (qName) {

           elementName = qName;

       }

       if ([elementName isEqualToString:@"user"]) {

           // 輸出屬性值

           NSLog(@"Name is %@ , Age is %@",[attributeDict objectForKey:@"name"], [attributeDictobjectForKey:@"age"]);

       }

   }

 

   - (void)parser:(NSXMLParser *)parser didEndElement:(NSString*)elementName namespaceURI:(NSString *)namespaceURI 

                                      qualifiedName:(NSString*)qName

   {

       // 元素終了句柄

       if (qName) {

              elementName = qName;

       }

   }

 

   - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string

   {

       // 取得元素的text

   }

 

   NSError *parseError = nil;

   [self parseXMLFileAtURL:[NSURL URLWithString:feedURLString]parseError:&parseError];

 

Iphone 實現畫折線圖

 

iphone裏面要畫圖一般都是通過CoreGraphics.framwork和QuartzCore.framwork實現,apple的官方sdkdemon中包含了QuartzCore的基本用法,

 

 HYPERLINK "http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/9GW3OBSTP0ZJNTH1WZU.jpg INCLUDEPICTURE "http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/9GW3OBSTP0ZJNTH1WZU_thumb.jpg" \* MERGEFORMATINET  HYPERLINK "http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/JOTBK2CLW5XTZSB.jpg INCLUDEPICTURE "http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/JOTBK2CLW5XTZSB_thumb.jpg" \* MERGEFORMATINET  HYPERLINK "http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/RRJN7VM2386UTRRD2S.jpg INCLUDEPICTURE "http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/RRJN7VM2386UTRRD2S_thumb.jpg" \* MERGEFORMATINET  HYPERLINK "http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/KG9ZH4_7G98_YG.jpg INCLUDEPICTURE "http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/KG9ZH4_7G98_YG_thumb.jpg" \* MERGEFORMATINET 

具體demo請參考 HYPERLINK "http://developer.apple.com/library/ios/" \l"samplecode/QuartzDemo/" \o "http://developer.apple.com/library/ios/#samplecode/QuartzDemo/"http://developer.apple.com/library/ios/#samplecode/QuartzDemo/

折線圖

 

 

要實現折線圖也就把全部的點連起來,movePointLineto,具體的調用裏面的api就可以實現了,但是畫座標就比較麻煩了,裏面需要去轉很多,好在國外有人開源了一個畫折線圖的開發包,首先看看效果吧,具體怎麼用可以參考作者git版本庫中的wiki。

 HYPERLINK"http://github.com/devinross/tapkulibrary/wiki/How-To-Use-This-Library"http://github.com/devinross/tapkulibrary/wiki/How-To-Use-This-Library

 HYPERLINK "http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/I0JWEMM2OL8WNWW7.jpg INCLUDEPICTURE "http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/I0JWEMM2OL8WNWW7_thumb.jpg" \* MERGEFORMATINET  HYPERLINK "http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/image131.png INCLUDEPICTURE "http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/image_thumb131.png" \* MERGEFORMATINET  HYPERLINK "http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/image132.png INCLUDEPICTURE "http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/image_thumb132.png" \* MERGEFORMATINET 

這個包還提供了其他的很好看的UI,都可以調來用,但是我們只需要一個畫圖要把整個包都導進去,工程太大了,既然是開源的那就想辦法提取出來吧,原先之前也有人幹過這樣的事。 HYPERLINK "http://duivesteyn.net/2010/03/07/iphone-sdk-implementing-the-tapku-graph-in-your-application/"http://duivesteyn.net/2010/03/07/iphone-sdk-implementing-the-tapku-graph-in-your-application/

我對源代碼進行簡單的修改,使其顯示座標之類的,更加符合工程的需要,但是還沒有實現畫多組數據,只能畫一組數據,不用viewContol,而使用addsubview,直接添加到當前的窗口,最終效果如下。

使用方法:

 HYPERLINK"http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/1Y6OW7ZKJ4GP4TXT2TW8.jpg

1.工程添加tk庫裏面的如下文件

 HYPERLINK "http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/7_F3J9_RC0SG6U8475PJ.jpg INCLUDEPICTURE "http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/7_F3J9_RC0SG6U8475PJ_thumb.jpg" \* MERGEFORMATINET 

2.添加QuartzCore  framework 

#import<QuartzCore/QuartzCore.h>

添加TapkuLibrary.bundle資源文件

3.代碼中完成實例,數據初始化就可以用了

 HYPERLINK "http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/2TKNVFWV48531GC8TG.jpg INCLUDEPICTURE "http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/2TKNVFWV48531GC8TG_thumb.jpg" \* MERGEFORMATINET 

 HYPERLINK"http://fly3q.com/wp-content/uploads/filedl/graph.zip"  HYPERLINK "http://commondatastorage.googleapis.com/fly3qpub/image/2010/09/image133.png" 下載修改後的版本。下次有時間在整理一個工程版本出來。

 

讓iPhone屏幕常亮不變暗的方法

 

如果您希望運行自己開發的App時,iPhone的屏幕不再自動變暗,可以使用以下方法讓屏幕常亮:iPhone OS用一個布爾值用來控制是否取消應用程序空閒時間:@property(nonatomic,getter=isIdleTime 

 

如果您希望運行自己開發的App時,iPhone的屏幕不再自動變暗,可以使用以下方法讓屏幕常亮:

 

 iPhone OS用一個布爾值用來控制是否取消應用程序空閒時間:@property(nonatomic,getter=isIdleTimerDisabled) BOOL idleTimerDisabled。這個值的默認屬性是"NO"。當大多數應用程序沒有接收到用戶輸入信息的時候,系統會把設備設置成“休眠”狀態,iPhone屏幕也會變暗。這樣做是爲了保存更多電量。事實上,應用程序在運行加速度遊戲的時候是不需要用戶輸入的,當然這裏只是一個假設,把這個變量設置爲"YES",來取消系統休眠的“空閒時間”。

 

重點是:你必須當真正需要的時候纔打開這個屬性當你不用的時候馬上還願成"NO"。大多數應用程序在休眠時間到的時候讓系統關閉屏幕。這個包括了有音頻的應用程 序。在Audio Session Services中使用適當的回放和記錄功能不會被間斷當屏幕關閉時。只有地圖應用程序,遊戲或者一些不間斷的用戶交互程序可以取消這個屬性。

 

蘋果開發網絡編程知識總結

 

以下蘋果開發網絡編程知識由 CocoaChina 會員cocoa_yang 總結,希望能爲蘋果開發新手梳理知識脈絡,節省入門時間。一:確認網絡環境3G/WIFI 1. 添加源文件和framework開發Web等網絡應用程序 

 

 以下蘋果開發網絡編程知識由 CocoaChina 會員“cocoa_yang” 總結,希望能爲蘋果開發新手梳理知識脈絡,節省入門時間。

 

一:確認網絡環境3G/WIFI

 

   1. 添加源文件和framework

   

   開發Web等網絡應用程序的時候,需要確認網絡環境,連接情況等信息。如果沒有處理它們,是不會通過Apple的審查的。

   Apple 的 例程 Reachability 中介紹了取得/檢測網絡狀態的方法。要在應用程序程序中使用Reachability,首先要完成如下兩部:

   

   1.1. 添加源文件:

   在你的程序中使用 Reachability 只須將該例程中的Reachability.h 和 Reachability.m 拷貝到你的工程中。如下圖:

   

   1.2.添加framework:

   將SystemConfiguration.framework 添加進工程。如下圖:

   

   

   2. 網絡狀態

   

   Reachability.h中定義了三種網絡狀態:

   typedef enum {

       NotReachable = 0,           //無連接

       ReachableViaWiFi,           //使用3G/GPRS網絡

       ReachableViaWWAN           //使用WiFi網絡

   } NetworkStatus;

   

   因此可以這樣檢查網絡狀態:

 

   Reachability *r = [ReachabilityreachabilityWithHostName:@“www.apple.com”];

   switch ([r currentReachabilityStatus]) {

           case NotReachable:

                   // 沒有網絡連接

                   break;

           case ReachableViaWWAN:

                   // 使用3G網絡

                   break;

           case ReachableViaWiFi:

                   // 使用WiFi網絡

                   break;

   }

   

   3.檢查當前網絡環境

 

   程序啓動時,如果想檢測可用的網絡環境,可以像這樣

   // 是否wifi

   + (BOOL) IsEnableWIFI {

       return ([[Reachability reachabilityForLocalWiFi]currentReachabilityStatus] != NotReachable);

   }

 

   // 是否3G

   + (BOOL) IsEnable3G {

       return ([[Reachability reachabilityForInternetConnection]currentReachabilityStatus] != NotReachable);

   }

   例子:

   - (void)viewWillAppear:(BOOL)animated {    

   if (([ReachabilityreachabilityForInternetConnection].currentReachabilityStatus == NotReachable)&&

           ([ReachabilityreachabilityForLocalWiFi].currentReachabilityStatus == NotReachable)) {

           self.navigationItem.hidesBackButton = YES;

           [self.navigationItemsetLeftBarButtonItem:nil animated:NO];

       }

   }

 

   4. 鏈接狀態的實時通知

 

   網絡連接狀態的實時檢查,通知在網絡應用中也是十分必要的。接續狀態發生變化時,需要及時地通知用戶:

   

   Reachability 1.5版本

   // My.AppDelegate.h

   #import "Reachability.h"

 

   @interface MyAppDelegate : NSObject <UIApplicationDelegate> {

       NetworkStatus remoteHostStatus;

   }

 

   @property NetworkStatus remoteHostStatus;

 

   @end

 

   // My.AppDelegate.m

   #import "MyAppDelegate.h"

 

   @implementation MyAppDelegate

   @synthesize remoteHostStatus;

 

   // 更新網絡狀態

   - (void)updateStatus {

       self.remoteHostStatus = [[Reachability sharedReachability]remoteHostStatus];

   }

 

   // 通知網絡狀態

   - (void)reachabilityChanged:(NSNotification *)note {

       [self updateStatus];

       if (self.remoteHostStatus == NotReachable) {

           UIAlertView *alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"AppName", nil)

                       message:NSLocalizedString (@"NotReachable", nil)

                      delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];

           [alert show];

           [alert release];

       }

   }

 

   // 程序啓動器,啓動網絡監視

   - (void)applicationDidFinishLaunching:(UIApplication *)application {

   

       // 設置網絡檢測的站點

       [[Reachability sharedReachability]setHostName:@"www.apple.com"];

       [[Reachability sharedReachability]setNetworkStatusNotificationsEnabled:YES];

       // 設置網絡狀態變化時的通知函數

       [[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(reachabilityChanged:)

                                              name:@"kNetworkReachabilityChangedNotification" object:nil];

       [self updateStatus];

   }

 

   - (void)dealloc {

       // 刪除通知對象

       [[NSNotificationCenter defaultCenter]removeObserver:self];

       [window release];

       [super dealloc];

   }

   

   Reachability 2.0版本

   

 

   // MyAppDelegate.h

   @class Reachability;

 

       @interface MyAppDelegate : NSObject<UIApplicationDelegate> {

           Reachability  *hostReach;

       }

 

   @end

 

   // MyAppDelegate.m

   - (void)reachabilityChanged:(NSNotification *)note {

       Reachability* curReach = [note object];

       NSParameterAssert([curReach isKindOfClass: [Reachabilityclass]]);

       NetworkStatus status = [curReachcurrentReachabilityStatus];

   

       if (status == NotReachable) {

           UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"AppName""

                            message:@"NotReachable"

                            delegate:nil

                            cancelButtonTitle:@"YES" otherButtonTitles:nil];

                            [alert show];

                            [alert release];

       }

   }

                            

   - (void)applicationDidFinishLaunching:(UIApplication *)application {

       // ...

                 

       // 監測網絡情況

       [[NSNotificationCenter defaultCenter] addObserver:self

                            selector:@selector(reachabilityChanged:)

                            name: kReachabilityChangedNotification

                            object: nil];

       hostReach = [[ReachabilityreachabilityWithHostName:@"www.google.com"] retain];

       hostReach startNotifer];

       // ...

   }

 

 

二:使用NSConnection下載數據

   

   1.創建NSConnection對象,設置委託對象

   

   NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:[NSURL URLWithString:[self urlString]]];

   [NSURLConnection connectionWithRequest:request delegate:self];

   

   2. NSURLConnection delegate委託方法

       - (void)connection:(NSURLConnection *)connectiondidReceiveResponse:(NSURLResponse *)response;  

       - (void)connection:(NSURLConnection *)connectiondidFailWithError:(NSError *)error;  

       - (void)connection:(NSURLConnection *)connectiondidReceiveData:(NSData *)data;  

       - (void)connectionDidFinishLoading:(NSURLConnection*)connection;  

 

   3. 實現委託方法

   - (void)connection:(NSURLConnection *)connectiondidReceiveResponse:(NSURLResponse *)response {

       // store data

       [self.receivedData setLength:0];           //通常在這裏先清空接受數據的緩存

   }

   

   - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {

          /* appends the new data to the received data */

       [self.receivedData appendData:data];       //可能多次收到數據,把新的數據添加在現有數據最後

   }

 

   - (void)connection:(NSURLConnection *)connectiondidFailWithError:(NSError *)error {

       // 錯誤處理

   }

 

   - (void)connectionDidFinishLoading:(NSURLConnection *)connection {

       // disconnect

       [UIApplicationsharedApplication].networkActivityIndicatorVisible = NO;  

       NSString *returnString = [[NSString alloc]initWithData:self.receivedData encoding:NSUTF8StringEncoding];

       NSLog(returnString);

       [self urlLoaded:[self urlString] data:self.receivedData];

       firstTimeDownloaded = YES;

   }

 

三:使用NSXMLParser解析xml文件

 

   1. 設置委託對象,開始解析

   NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];   //或者也可以使用initWithContentsOfURL直接下載文件,但是有一個原因不這麼做:

   // It's also possible to have NSXMLParser download the data, by passingit a URL, but this is not desirable

   // because it gives less control over the network, particularly inresponding to connection errors.

   [parser setDelegate:self];

   [parser parse];

 

   2. 常用的委託方法

   - (void)parser:(NSXMLParser *)parser didStartElement:(NSString*)elementName

                              namespaceURI:(NSString *)namespaceURI

                              qualifiedName:(NSString *)qName

                              attributes:(NSDictionary *)attributeDict;

   - (void)parser:(NSXMLParser *)parser didEndElement:(NSString*)elementName

                              namespaceURI:(NSString *)namespaceURI

                              qualifiedName:(NSString *)qName;

   - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string;

   - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError*)parseError;

 

   static NSString *feedURLString =@"http://www.yifeiyang.net/test/test.xml";

 

   3.  應用舉例

   - (void)parseXMLFileAtURL:(NSURL *)URL parseError:(NSError **)error

   {

       NSXMLParser *parser = [[NSXMLParser alloc]initWithContentsOfURL:URL];

       [parser setDelegate:self];

       [parser setShouldProcessNamespaces:NO];

       [parser setShouldReportNamespacePrefixes:NO];

       [parser setShouldResolveExternalEntities:NO];

       [parser parse];

       NSError *parseError = [parser parserError];

       if (parseError && error) {

           *error = parseError;

       }

       [parser release];

   }

 

   - (void)parser:(NSXMLParser *)parser didStartElement:(NSString*)elementName namespaceURI:(NSString *)namespaceURI

                                     qualifiedName:(NSString*)qName attributes:(NSDictionary *)attributeDict{

       // 元素開始句柄

       if (qName) {

           elementName = qName;

       }

       if ([elementName isEqualToString:@"user"]) {

           // 輸出屬性值

           NSLog(@"Name is %@ , Age is %@",[attributeDict objectForKey:@"name"], [attributeDictobjectForKey:@"age"]);

       }

   }

 

   - (void)parser:(NSXMLParser *)parser didEndElement:(NSString*)elementName namespaceURI:(NSString *)namespaceURI

                                      qualifiedName:(NSString*)qName

   {

       // 元素終了句柄

       if (qName) {

              elementName = qName;

       }

   }

 

   - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string

   {

       // 取得元素的text

   }

 

   NSError *parseError = nil;

   [self parseXMLFileAtURL:[NSURL URLWithString:feedURLString]parseError:&parseError];

 

如何隱藏狀態欄 

[UIApplication sharedApplication ].statusBarHidden = YES;

 

.m 文件與.mm文件的區別 

.m文件是object-c文件

.mm文件相當於c++或者c文件

 

NSLog(@"afd")與 NSLog("afd")

 

細微差別會導致程序崩潰。

 

但是我不太明白爲何蘋果要把編譯器做的對這兩種常量有區別。

 

不過值得一提的是可能爲了方便蘋果自身的NSObject對象的格式化輸出。

 

safari其實沒有把內存的緩存寫到存儲卡上 

 

NSURLCachedoesn't seem to support writing to disk on iPhone. The documentation forNSCachedURLResponse says that the NSURLCacheStoragePolicy"NSURLCacheStorageAllowed" is treated as"NSURLCacheStorageAllowedInMemoryOnly" by iPhone OS. 

 

官方文檔是這麼說的。

 

爲了證明這個,我找到了一個目錄。

 

/private/var/mobile/Library/Caches/Safari/Thumbnails

 

隨機數的使用

 

       頭文件的引用

       #import <time.h>

       #import <mach/mach_time.h>

 

       srandom()的使用

       srandom((unsigned)(mach_absolute_time() &0xFFFFFFFF));

 

       直接使用 random() 來調用隨機數

 

在UIImageView 中旋轉圖像

 

       float rotateAngle = M_PI;

       CGAffineTransform transform=CGAffineTransformMakeRotation(rotateAngle);

       imageView.transform = transform;

      

       以上代碼旋轉imageView, 角度爲rotateAngle,方向可以自己測試哦!

 

 

在Quartz中如何設置旋轉點

 

       UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"bg.png"]];

       imageView.layer.anchorPoint = CGPointMake(0.5, 1.0);

 

       這個是把旋轉點設置爲底部中間。記住是在QuartzCore.framework中才得到支持。

 

創建.plist文件並存儲

 

       NSString *errorDesc;  //用來存放錯誤信息

       NSMutableDictionary *rootObj = [NSMutableDictionarydictionaryWithCapacity:4]; //NSDictionary, NSData等文件可以直接轉化爲plist文件

       NSDictionary *innerDict;

       NSString *name;

       Player *player;

       NSInteger saveIndex;

   

       for(int i = 0; i < [playerArray count]; i++) {

             player = nil;

             player = [playerArrayobjectAtIndex:i];

             if(player == nil)

                    break; 

             name = player.playerName;// This"Player1" denotes the player name could also be the computer name

             innerDict = [selfgetAllNodeInfoToDictionary:player];

             [rootObj setObject:innerDictforKey:name]; // This "Player1" denotes the person who start thisgame

       }

       player = nil;

       NSData *plistData = [NSPropertyListSerializationdataFromPropertyList:(id)rootObj format:NSPropertyListXMLFormat_v1_0errorDescription:&errorDesc];

 

       紅色部分可以忽略,只是給rootObj添加一點內容。這個plistData爲創建好的plist文件,用其writeToFile方法就可以寫成文件。下面是代碼:

       

       /*得到移動設備上的文件存放位置*/

       NSString *documentsPath = [selfgetDocumentsDirectory]; 

       NSString *savePath = [documentsPathstringByAppendingPathComponent:@"save.plist"];

   

       /*存文件*/

       if (plistData) {

               [plistDatawriteToFile:savePath atomically:YES];

        }

        else {

               NSLog(errorDesc);

               [errorDesc release];

       }

 

       - (NSString *)getDocumentsDirectory {  

               NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);  

               return [pathsobjectAtIndex:0];  

       } 

 

讀取plist文件並轉化爲NSDictionary

 

       NSString *documentsPath = [self getDocumentsDirectory];

       NSString *fullPath = [documentsPathstringByAppendingPathComponent:@"save.plist"];

       NSMutableDictionary* plistDict = [[NSMutableDictionaryalloc] initWithContentsOfFile:fullPath];

 

讀取一般性文檔文件

 

       NSString *tmp;

       NSArray *lines; /*將文件轉化爲一行一行的*/

       lines = [[NSString   stringWithContentsOfFile:@"testFileReadLines.txt"] 

                     componentsSeparatedByString:@"\n"];

   

        NSEnumerator *nse = [lines objectEnumerator];

   

        // 讀取<>裏的內容

        while(tmp = [nse nextObject]) {

                 NSString*stringBetweenBrackets = nil;

                 NSScanner *scanner =[NSScanner scannerWithString:tmp];

                 [scannerscanUpToString:@"<" intoString:nil];

                 [scannerscanString:@"<" intoString:nil];

                 [scannerscanUpToString:@">" intoString:&stringBetweenBrackets];

 

                NSLog([stringBetweenBrackets description]);

         }

 

對於讀寫文件,還有補充,暫時到此。隨機數和文件讀寫在遊戲開發中經常用到。所以把部分內容放在這,以便和大家分享,也當記錄,便於查找。

 

隱藏NavigationBar

[self.navigationControllersetNavigationBarHidden:YES animated:YES];

 

在想隱藏的ViewController中使用就可以了。

 

如何在iPhone程序中調用外部命令 

 

下面是如何在iPhone非官方SDK程序中調用外部命令的方法。 

 

- (NSString * ) executeCommand : ( NSString * ) cmd { NSString * output = [NSString string ] ; FILE * pipe = popen ( [ cmd cStringUsingEncoding :NSASCIIStringEnc

 

下面是如何在iPhone非官方SDK程序中調用外部命令的方法。

 

-(NSString *)executeCommand: (NSString *)cmd

{

   NSString *output = [NSString string];

   FILE *pipe = popen([cmd cStringUsingEncoding: NSASCIIStringEncoding],"r");

   if (!pipe) return;

 

   char buf[1024];

   while(fgets(buf, 1024, pipe)) {

   output = [output stringByAppendingFormat: @"%s", buf];

}

 

pclose(pipe);

returnoutput;

}

 

NSString*yourcmd = [NSString stringWithFormat: @"your command"];

[selfexecuteCommand: yourcmd];

 

如何在iPhone程序讀取數據時顯示進度窗

 

下面代碼說明如何使用iPhone 非官方SDK在讀取數據時顯示進度條。

 

以下代碼參考了MobileRss。

 

定義頭文件:

 

#import"uikit/UIProgressHUD.h"

 

@interfaceEyeCandy : UIApplication {

 UIProgressHUD*progress;

}

 

- (void)showProgressHUD:(NSString *)label withWindow:(UIWindow *)w withView:(UIView *)vwithRect:(struct CGRect)rect;

- (void)hideProgressHUD;

 

.@end

 

上面的引號要改成<>。

 

import"EyeCandy.h"

 

@implementationEyeCandy

-(void)showProgressHUD:(NSString *)label withWindow:(UIWindow *)wwithView:(UIView *)v withRect:(struct CGRect)rect

{

 progress= [[UIProgressHUD alloc] initWithWindow: w];

 [progresssetText: label];

 [progressdrawRect: rect];

 [progressshow: YES];

 

 [vaddSubview:progress];

}

 

-(void)hideProgressHUD

{

 [progressshow: NO];

 [progressremoveFromSuperview];

}

 

@end

 

使用下面代碼調用:

 

// SetupEye Candy View

_eyeCandy= [[[EyeCandy alloc] init] retain];

 

// Callloading display

[_eyeCandyshowProgressHUD:@"Loading …" withWindow:window withView:mainViewwithRect:CGRectMake(0.0f, 100.0f, 320.0f, 50.0f)];

 

// Whenfinished for hiding the &quot;loading text&quot;

[_eyeCandyhideProgressHUD];

 

WebKit的基本用法 

 

WebKit是蘋果開發中比較常用的瀏覽器引擎,Safari使用的正是WebKit引擎。WebKit基於KDE的KHTML加以再開發,解析速度超過了以往所有的瀏覽器。這裏簡單記錄一下WebKit的基本用法。

 

WebKit由下面的結構組成:

 

•DomCore 

•JavaScriptCore 

•WebCore 

一般瀏覽

 

要打開網頁,可以這樣做:

 

1.[[webViewmainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURLURLWithString:urlText]]];

DomCore

 

DomCore用於處理DOM文檔,包括:

 

•DOMDocument 

•DOMNamedNodeMap 

•DOMNode 

•DOMNodeList 

要獲取一個DOMDocument,可以這樣做:

 

1.DOMDocument*myDOMDocument = [[webView mainFrame] DOMDocument];

要用於HTML處理,可以使用DOMHTMLDocument(MacOS X 10.4之後),獲取方式相同:

 

1.DOMHTMLDocument*myDOMDocument = (DOMHTMLDocument*)[[webView mainFrame] DOMDocument];

方法定義:

 

蘋果的WebKit更新說明

 

JavaScriptCore

 

在WebKit中執行腳本的方法:

 

1.WebScriptObject*myscript = [webView windowScriptObject];

2.NSString*script = @"alert('hello');";

3.[myscriptevaluateWebScript script];

參考:

 

http://www.macgood.com/thread-24636-1-1.html

 

http://www.cocoadev.com/index.pl?WebKit

 

爲什麼不要做iPhone上面的應用

 

簡單來說就是因爲兩國的文化不同,或者說生活方式的不同。美國不管多窮的人都有車,他們平時的生活方式和國內絕對是完全不同的。做應用和做遊戲不一樣,應用需要滿足人們某一

簡單來說就是因爲兩國的文化不同,或者說生活方式的不同。美國不管多窮的人都有車,他們平時的生活方式和國內絕對是完全不同的。做應用和做遊戲不一樣,應用需要滿足人們某一部分的需求,比如,一個計算小費的軟件,在國內不會有市場,可是美國人都有一個。

大家可以設身處地的想一下,誰會需要你做的軟件,這樣的人有多少,這樣的人又有iPhone的又有多少。

 

對於應用來說,針對商務人士的又比針對普通人的好,基本上商務人士不太在乎幾塊錢一個軟件,這也是backup assistant賣得最好的一個原因。這個軟件一年的年費24美元,大約有數千萬美元一年的收入。什麼樣的應用軟件是這些人需要的?連筆者自己也不太清楚,筆者雖然已經在美國工作了多年,但是對於美國文化的瞭解還處於一知半解狀態,更不用說正在留學的學生了。

 

還有一個能成功的應用軟件是你已經有非常多的數據,比如你有當地的所有加油站的信息,做一個油價的地圖軟件,顯然市場會不錯。不過數據要是美國的數據,國內的沒有太大的幫助。

 

綜上所述,遊戲比應用好做很多,如果要作應用的話,可以從單機的小應用開始。要在美國運營一個支持10萬人的網絡應用,沒有30萬美元絕對沒戲。如果非要上,只能早死早超生了。

 

獲取iPhone用戶手機號

 

使用下面的函數可以返回用戶的手機號:

 

externNSString *CTSettingCopyMyPhoneNumber();

 

然後調用即可。

 

由於這個函數是包含在CoreTelephony中,所以只能用於非官方iPhone SDK。

 

在程序中關閉iPhone

首先在程序中引用 #include sys/reboot.h 然後使用reboot(RB_HALT); 就可以直接將iPhone關機。

 

首先在程序中引用

 

#include<sys/reboot.h>

 

然後使用

 

reboot(RB_HALT);

 

就可以直接將iPhone關機。

 

convertthe contents of an NSData object to an NSString

 

1.NSString *stringFromASC = [NSString stringWithCString:[ascData bytes]length:[ascData length]];

 

If theNSData object contains unichar characters then do this:

 

NSString*stringFromUnichar = [NSString stringWithCharacters:[unicharData bytes]length:[unicharData length] / sizeof(unichar)];

 

2. -(id)initWithData:(NSData *)data encoding:(NSStringEncoding)encoding

 

iPhone的特殊URL

在iPhone中,可以直接用UIApp打開URL地址。如下所示:

 

1.[ UIAppopenURL: [ NSURL URLWithString:@"http://www.apple.com" ] ];

或者:

 

1.[ UIAppopenURL: [ NSURL URLWithString:@"mailto:[email protected]?Subject=hello"] ];

與此同時,iPhone還包含一些其他除了http://或者mailto:之外的URL: 

 

sms://可以調用短信程序

 

tel://可以撥打電話

 

itms://可以打開MobileStore.app

 

audio-player-event://可以打開iPod

 

audio-player-event://?uicmd=show-purchased-playlist可以打開iPod播放列表

 

video-player-event://可以打開iPod中的視頻

 

 

getiphone uniqueIdentifier

 

I alsofind that I can get uniqueIdentifier using:

 

UIDevice*myDevice = [UIDevice currentDevice];NSString *identifier =myDevice.uniqueIdentifier;

 

 

打開本地網頁,與遠程網頁

 

fileURLWithPath:Initializesand returns a newly created NSURL object as a file URL with a specified path.

 

+(id)fileURLWithPath:(NSString *)path

 

URLWithString:

Createsand returns an NSURL object initialized with a provided string.

 

+(id)URLWithString:(NSString *)URLString

 

教你如何使用UIWebView

 

Start byopening up the WebBrowserTutorialAppDelegate.h file and editing the @interfaceline to read:

 

@interfaceWebBrowserTutorialAppDelegate : NSObject <UIWebViewDelegate> {

What wehave done is to make the main AppDelegate a delegate for the UIWebView as well.

 

Now weneed to set our webView to have the main AppDelegate as its delegate, you cando this by opening up WebBrowserTutorialAppDelegate.m and putting the followingline just inside theapplicationDidFinishLaunching function:

 

webView.delegate= self;

That isall pretty self explanatory, it just sets the delegate of our webView to self,which in this case is our main application delegate.

 

Now we arepretty much done, we just need to add the function to catch the link clicks. Todo this we need to add a new function, copy the content below to theWebBrowserTutorialAppDelegate.m file:

 

-(BOOL)webView:(UIWebView*)webViewshouldStartLoadWithRequest:(NSURLRequest*)requestnavigationType:(UIWebViewNavigationType)navigationType {

NSURL *url= request.URL;

NSString*urlString = url.absoluteString;

NSLog(urlString);

returnYES;

}

Thisfunction will catch all requests and allow you to either manipulate them andpass them on or to perform your own custom action and stop the event frombubbling.

 

The firstline gets the URL of the request, this is the contents inside the hrefattribute in the anchor tag.

The nextline converts the URL to a string so we can log it out. You can access manyparts of the NSURL, here are some of them and brief description of what theydo.

 

*absoluteString - An absolute string for the URL. Creating by resolving thereceiver’s string against its base.

*absoluteURL - An absolute URL that refers to the same resource as the receiver.If the receiver is already absolute, returns self.

* baseURL- The base URL of the receiver. If the receiver is an absolute URL, returnsnil.

* host -The host of the URL.

*parameterString - The parameter string of the URL.

* password- The password of the URL (i.e. http://user:[email protected]would return pass)

* path -Returns the path of a URL.

* port -The port number of the URL.

* query -The query string of the URL.

*relativePath - The relative path of the URL without resolving against the baseURL. If the receiver is an absolute URL, this method returns the same value aspath.

*relativeString - string representation of the relative portion of the URL. Ifthe receiver is an absolute URL this method returns the same value asabsoluteString.

* scheme -The resource specifier of the URL (i.e. http, https, file, ftp, etc).

* user -The user portion of the URL.

 

Then thethird line simply logs the URL to the console, so you will new to open up theconsole while you run this in the simulator to see the results.

 

Finallythe forth line returns YES, this will allow the UIWebView to follow the link,if you would just like to catch a link and stop the UIWebView from following itthen simply return NO.

 

UIBUtton title image 不能同時顯示

 

[leftbutton setTitle:_(@"About") forState:UIControlStateNormal ];

 

 

[leftbutton setImage:image forState:UIControlStateNormal ];

 

不能同時顯示。

 

其他控件如:UINavigatonItem

 

不要在語言包裏面設置空格

有時,爲了界面的需要,我們不要在語言包裏面加空格,要在程序中進行控制。

buttonTitle= [ NSString stringWithFormat:@"        %@",_(@"updateWeb") ];

 

NSNotificationCenter 帶參數發送

 

MPMoviePlayerController*theMovie = [[MPMoviePlayerController alloc]initWithContentURL:[NSURLfileURLWithPath:[[[tableTitles objectForKey:keyIndex] objectAtIndex:row]objectAtIndex:3] ]];

 

[[NSNotificationCenterdefaultCenter] addObserver:self selector:@selector(myMovieFinishedCallback:)name:MPMoviePlayerPlaybackDidFinishNotification object:theMovie];

 

[theMovieplay];

 

-(void)myMovieFinishedCallback:(NSNotification*)aNotification

 

{

 

    MPMoviePlayerController *theMovie = [aNotification object];

 

  [[NSNotificationCenter defaultCenter] removeObserver:self          name:MPMoviePlayerPlaybackDidFinishNotification object:theMovie];

 

  // Release the movie instance [theMovie release];

 

}

 

------------

 

MPMoviePlayerController*theMovie = [[MPMoviePlayerController alloc]initWithContentURL:[NSURLfileURLWithPath:[[[tableTitles objectForKey:keyIndex] objectAtIndex:row]objectAtIndex:3] ]];

 

[[NSNotificationCenterdefaultCenter] addObserver:self selector:@selector(myMovieFinishedCallback:)name:MPMoviePlayerPlaybackDidFinishNotification object:theMovie userInfo:dic];

 

[theMovieplay];

 

-(void)myMovieFinishedCallback:(NSNotification*)aNotification

 

{

 

MPMoviePlayerController*theMovie = [aNotification object];

 

[[NSNotificationCenterdefaultCenter] removeObserver:selfname:MPMoviePlayerPlaybackDidFinishNotification object:theMovie];

 

// Releasethe movie instance [theMovie release];

 

}

 

延時一段時間執行某一函數

 

[selfperformSelector:@selector(dismissModal) withObject:self afterDelay:1.0];

 

無99美金證書聯機開發

第一步:進入 cd/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.1.sdk/ sudo viSDKSettings.plist,將CODE_SIGNING_REQUIRED的值改成NO.保存後退出.

 

第二步:重新啓動XCode項目.

 

第三步:右擊項目GetInfo.將Code Signing下的CodeSigning Identity值設置成Don't Code Sign, 將CodeSigning Identity下的Any iOS Device的值設置成空.

 

獲取IOS設備的基本信息

系統唯一標識 

是什麼設備:iPad還是iPhone等 

iOS版本號 

系統名稱 

 

[[UIDevicecurrentDevice] uniqueIdentifier], 

                     [[UIDevice currentDevice] localizedModel], 

                     [[UIDevice currentDevice] systemVersion], 

                     [[UIDevice currentDevice] systemName], 

                     [[UIDevice currentDevice] model]];

 

用NSDateFormatter調整時間格式的代碼

 

在開發iOS程序時,有時候需要將時間格式調整成自己希望的格式,這個時候我們可以用NSDateFormatter類來處理。

例如:

 

//實例化一個NSDateFormatter對象

 

NSDateFormatter*dateFormatter = [[NSDateFormatter alloc] init];

 

//設定時間格式,這裏可以設置成自己需要的格式

 

[dateFormattersetDateFormat:@"yyyy-MM-dd HH:mm:ss"];

 

//用[NSDatedate]可以獲取系統當前時間

 

NSString*currentDateStr = [dateFormatter stringFromDate:[NSDate date]];

 

//輸出格式爲:2010-10-2710:22:13

 

NSLog(@”%@”,currentDateStr);

 

//alloc後對不使用的對象別忘了release

 

[dateFormatterrelease];

 

UIView設置成圓角方法

 

m_mainImgView.layer.cornerRadius= 6;

m_mainImgView.layer.masksToBounds= YES;

 

iPhone裏的frame和bounds區別

 

 INCLUDEPICTURE"http://hiphotos.baidu.com/shiqyn/pic/item/efb90234802f1089d1a2d38e.jpg"\* MERGEFORMATINET 

 

Objective-C內存管理

 

在使用Objective-C的工作中內存管理是首先要學會的一項技能,是如此重要,就好比是男人就要追漂亮姑娘一樣~~下面就來聊聊Apple官網上的內存管理的事情。

 

Objective-C的對象內存管理是一件非常有意思的事情,由其是在iPhone嵌入式設備中.

 

想玩的省心點,就得熟知它的管理規則,由其是內存的管理機制。瞭解它的品性了才能在Cocoa的世界裏如魚得水。否則,反之(如水得魚!!^_^)。

 

首先,要牢記Apple的官網上的內存管理三定律:

 

1,一個對象可以有一個或多個擁有者

 

2,當它一個擁有都都沒有時,它就會被回收

 

3,如果想保留一個對象不被回收,你就必需成爲它的擁有者

 

 

所有內存管理的原則全在這裏!!

 

簡單??哈哈!

 

名人曰:“大道至簡”

 

這兒玩意兒說起來比過家家還容易,但其實有些事情真正做起來並不是簡單的事兒~~

 

咱們首先來說怎麼樣才能成爲一個對象的擁有者。Cocoa提供了一個機制叫"referencecounting",翻譯過來就是“關聯記數器”(自己翻譯的,真不知叫啥,如果有官方的翻譯請通知我)。每一個對象都有一個關聯記數的值。當它被創建時,它的值爲“1”。當值減少到“0”時,就會被回收(調用它的deallocate方法,如果沒有寫,則調用從NSObject繼承而來的回收方法,下文有說,一定要重寫該方法)。以下幾個方法可以操作這個記數:

 

1,alloc

  爲對象分配內存,記數設爲“1”,並返回此對象。

 

2,copy

  複製一個對象,此對象記數爲“1”,返回此對象。你將成爲此克隆對象的擁有者

 

3,retain

  對象“關聯記數”加“1”,併成爲此對象的擁有者。

 

4,release

  對象“關聯記數”減“1”,並丟掉此對象。

 

5,autorelease

 

  在未來的某一時刻,對象“關聯記數”減“1”。並在未來的某個時間放棄此對象。

 

有了上面的幾個方法(當然這也是所有的內存操作的方法,簡單吧,哈哈哈)你就可以隨意操作一個對象的記數。並部分或完全的控制它的生命週期。但實際應用中,隨意亂寫上面的任何一個方法都可能會帶來嚴重的內存泄露。混亂的內存分配等於沒完沒了的麻煩工作,你不想在情人節的日子還在爲記數之類的鳥問題而丟了老婆吧~~哈哈哈,爲了美麗溫柔賢惠又善解人意的準老婆請牢記以下四條:

 

1,一個代碼塊內要確保copy,alloc 和 retain 的使用數量與 release 和autorelease 的數量。

 

2,在使用以“alloc”或“new”開頭或包含“copy”的方法,或“retain”一個對象時,你就會變爲它的擁有者。

 

3,實現“dealloc”方法,並施放所有的實例變量。(其實這裏還有很多的巧兒門!!)

 

4,永不自己調用“dealloc”方法,這是系統當“retain”減到“0”時,自動調用的。手動調用會引起retain count記數錯誤(多一次的release)。

 

其實做到這些也不難,

 

retaincount 增加與減少的方法對應,板丁板做到了就行了。

 

來自:http://blog.csdn.net/dboylx/archive/2009/02/13/3888746.aspx

 

iphone更改鍵盤右下角按鍵的type

 

以UISearchBar爲例。

 

 

創建mySearchBar:

 

mySearchBar= [[UISearchBar alloc] initWithFrame:CGRectMake(0.0, 0,320, SEARCH_HEIGHT)];

mySearchBar.placeholder= curPath;

[mySearchBarsetDelegate:self];

//tableView.tableHeaderView=mySearchBar;

[self.viewaddSubview:mySearchBar];

 

 

更改按鍵的keyType(默認是return,這裏將它更改成done,當然還可以更改成其他的):

UITextField*searchField = [[mySearchBar subviews] lastObject];

[searchFieldsetReturnKeyType:UIReturnKeyDone];

[mySearchBarrelease];

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章