這份筆記把 iOS 學習路徑上最常接觸的知識點重新編排成清晰的章節:先建立 Cocoa Touch 的整體觀念,再依序梳理視圖與控制項、容器控制器、滾動與列表、資料持久化、多執行緒、網路通訊、多媒體、繪圖動畫、地圖,最後補上記憶體管理與 Cocos2d 遊戲開發的入門要點。
Foundation 是 Cocoa 中最基礎的一層,負責物件管理、記憶體管理與字串、集合等容器型別。
UIKit 為程式提供視覺化的底層架構,包含視窗、視圖、控制項以及管理它們的控制器;同層的其他框架還能存取聯絡人、相簿、加速器等裝置能力。
而 UIViewController 就是連接 Model 與 View 的橋樑。
App 中看得到、摸得到的都是視圖,相當於 Java 中的容器概念;viewController 則是承載它們的底板。
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 280, 420)]; [self.view addSubview:view];
子視圖先加入的在下層、後加入的在上層。由於 UI 中的控制項都是視圖的子類,因此可以任意嵌套;把一批視圖裝進同一個父視圖,主要是為了保證整體性(例如整體移動、整體隱藏)。
幾個關鍵概念要分清:
· frame:相對於父視圖的座標與尺寸;
· bounds:視圖自身的邊界座標;
· center:中心點在父視圖中的相對位置。
button.bounds = CGRectMake(0, 0, 50, 50); button.center = CGPointMake(160, 230);
層次操作常用的方法:
[button1 exchangeSubviewAtIndex:0 withSubviewAtIndex:1]; // 交換位置 [button1 insertSubview:label3 atIndex:1]; // 插入到指定索引 [button1 insertSubview:label2 aboveSubview:label1]; // 插到某視圖上方 [label2 removeFromSuperview]; // 從父視圖移除 [button1 bringSubviewToFront:label1]; // 置頂 [button1 sendSubviewToBack:label1]; // 置底 [label1 isDescendantOfView:button1]; // 是否為子視圖
其他常用屬性:tag 作為視圖標識(可用 viewWithTag: 反查)、hidden 控制隱藏(父視圖隱藏則子視圖一起消失)、clipsToBounds 裁切超出邊界的子視圖、autoresizingMask 控制子視圖隨父視圖伸縮。
CGRect rect = {0, 100, 100, 40};
UILabel *label = [[UILabel alloc] initWithFrame:rect];
label.font = [UIFont systemFontOfSize:20]; // 字型與大小
label.textColor = [UIColor redColor]; // 文字顏色
label.textAlignment = NSTextAlignmentLeft; // 對齊方式
label.adjustsFontSizeToFitWidth = YES; // 自動縮放字級
label.minimumFontSize = 10; // 縮放下限
label.numberOfLines = 3; // 行數限制
label.lineBreakMode = NSLineBreakByTruncatingHead; // 截頭,另有截尾與中間截
label.highlighted = YES; // 高亮狀態
label.highlightedTextColor = [UIColor whiteColor];
label.shadowColor = [UIColor blackColor]; // 陰影顏色
label.shadowOffset = CGSizeMake(-2, -2); // 陰影偏移
lineBreakMode 還有兩種常見取值:Clip 表示寫多少算多少、不加省略符;CharacterWrap 按字元換行、WordWrap 以單詞為單位換行以保持單詞完整性。
button 可以透過同名類別方法建立,這種方式不是 alloc 出來的,不需要手動釋放:
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button1.frame = CGRectMake(120, 280, 80, 40); [button1 setTitle:@"click here" forState:UIControlStateNormal]; [button1 setTitle:@"click ready" forState:UIControlStateHighlighted]; [button1 setTitle:@"forbid using" forState:UIControlStateDisabled]; button1.enabled = NO; button1.titleLabel.font = [UIFont systemFontOfSize:20]; [button1 setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal]; [button1 addTarget:self action:@selector(onclick:) forControlEvents:UIControlEventTouchUpInside];
addTarget 的第一個參數是觸發對象,action 是觸發的方法,forControlEvents 決定哪種互動會觸發。若希望方法能拿到 button 本身,把 sender 作為參數傳入即可——注意帶參數的 selector 名稱末尾要有冒號。
圖片相關:setBackgroundImage:forState: 設背景圖、setImage:forState: 設圖示;image.size 可取得圖片尺寸。另外 TouchDragInside / TouchDragOutside 這類事件可以用來實作「手指滑進滑出按鈕」的觸控效果。
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"2.jpg"]]; imageView.frame = CGRectMake(20, 20, 140, 220); imageView.contentMode = UIViewContentModeScaleAspectFit; // 按比例填充 imageView.userInteractionEnabled = YES; // 預設為 NO,要加手勢必須打開
contentMode 的三種常見取值:ScaleAspectFit(按比例適配、留白)、ScaleAspectFill(按比例填滿、可搭配 clipsToBounds 裁切)、ScaleToFill(直接拉伸填滿)。
手勢辨識器的標準三步:建立辨識器 → 設定屬性 → 加到視圖上。
UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onclick)]; tgr.numberOfTapsRequired = 1; // 單擊 tgr.numberOfTouchesRequired = 1; // 觸點數 [imageView addGestureRecognizer:tgr];
移動手勢要注意 translation 必須清零,否則位移會累加成兩倍:
-(void)pan:(UIPanGestureRecognizer *)pan {
CGPoint point = [pan translationInView:self.view];
imageView.center = CGPointMake(imageView.center.x + point.x, imageView.center.y + point.y);
[pan setTranslation:CGPointMake(0, 0) inView:self.view];
}
縮放手勢要記錄原始尺寸,並在手勢結束時更新基準值,最後把 scale 歸回 1.0:
-(void)pinch:(UIPinchGestureRecognizer *)pinch {
imageView.bounds = CGRectMake(0, 0, size.width * pinch.scale, size.height * pinch.scale);
if (pinch.state == UIGestureRecognizerStateEnded) {
size = imageView.bounds.size;
}
pinch.scale = 1.0f;
}
旋轉手勢同理,需要在結束時把角度累加保存,否則物件會跳回初始角度:
-(void)rotation:(UIRotationGestureRecognizer *)rotation {
imageView.transform = CGAffineTransformMakeRotation(f + rotation.rotation);
if (rotation.state == UIGestureRecognizerStateEnded) {
f = f + rotation.rotation;
}
}
兩者都是視圖,透過 delegate 回報輸入狀態。使用時別忘了在標頭檔宣告協議,並把 delegate 設為自己。
UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(40, 20, 250, 60)];
field.placeholder = @"username"; // 佔位文字
field.clearButtonMode = UITextFieldViewModeAlways;
field.secureTextEntry = YES; // 密碼輸入
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder]; // 收起鍵盤
return NO;
}
// 限制輸入長度:string 是這次輸入的內容,textField.text 尚未包含它
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (string.length > 0) {
return textField.text.length < 10;
}
return YES;
}
UITextView 的代理介面幾乎相同,差異在於多了 textViewDidChange: 與 textViewDidChangeSelection:。它另外支援 keyboardType、returnKeyType、autocorrectionType、autocapitalizationType 等鍵盤行為設定。
常見有兩種做法。第一種是把新控制器的視圖加進當前視圖並成為子控制器:
ViewController2 *vc2 = [[ViewController2 alloc] init]; vc2.view.frame = CGRectMake(0, 0, 320, 460); [self.view addSubview:vc2.view]; [self addChildViewController:vc2]; // 用完後成對清理 [vc2.view removeFromSuperview]; [vc2 removeFromParentViewController];
第二種是以模態方式呈現,動畫由系統處理,程式碼更乾淨:
[self presentModalViewController:vc2 animated:YES]; [self dismissModalViewControllerAnimated:YES];
而如果是巢狀在 UINavigationController 中,則直接用 push / pop:
[self.navigationController pushViewController:third animated:YES];
本文以 UIBarButtonItem 的四種建立方式說明導航列按鈕:標題、圖片、自訂視圖、系統樣式。其中自訂視圖的方式最靈活,能做出無邊框的純圖示按鈕:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; [button setImage:[UIImage imageNamed:@"5.png"] forState:UIControlStateNormal]; button.frame = CGRectMake(0, 0, 30, 30); // 必須設定 frame,否則不顯示 [button addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:button];
導航列的其他常用設定:navigationItem.prompt 加副標題、rightBarButtonItems 一次放多個按鈕、navigationBar.tintColor 改色調、translucent 與 alpha 控制透明度、setBackgroundImage:forBarMetrics: 換背景圖、setNavigationBarHidden:animated: 隱藏、hidesBackButton 去掉返回鈕。
UIToolbar 的特別之處在於它的 hidden 預設是 YES,加上去之後記得設為 NO。若要每一頁都有工具列,可以在 UINavigationController 上打開 toolbarHidden。
標籤控制器的組裝順序是:建立各個子控制器 → 為它們設定 tabBarItem → 組裝成陣列交給 viewControllers → 設為 rootViewController。
UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"首頁" image:[UIImage imageNamed:@"home.png"] tag:0]; self.vc01.tabBarItem = item; self.vc01.tabBarItem.badgeValue = @"3"; // 紅點提示,設為 nil 即清空 UITabBarController *tabBar = [[UITabBarController alloc] init]; tabBar.viewControllers = [NSArray arrayWithObjects:self.vc01, self.vc02, nil]; self.window.rootViewController = tabBar;
這裡有個經典的坑:如果把標籤的設定寫在 viewDidLoad 中,由於系統為省記憶體只會先載入第一個控制器,導致只有第一個標籤顯示正常。解法是把標籤設定移到 init 方法中,或在 AppDelegate 中統一建立。
NSUserDefaults 是最輕量的持久化方案,可儲存 NSString、NSNumber、NSData、NSArray、NSDictionary,注意最後要呼叫 synchronize 才會真正落盤:
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults]; [ud setObject:@"adba" forKey:@"key"]; [ud synchronize]; NSString *str = [ud objectForKey:@"key"];
它也是記住「上次停留在第幾頁」的正統做法——在 tabBarController:didSelectViewController: 中把 selectedIndex 存起來,啟動時再讀回來。
滾動視圖的四個關鍵屬性:
UIScrollView *sv = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)]; sv.contentSize = CGSizeMake(320, 460 * 2); // 內容尺寸,決定可滾動範圍 sv.contentOffset = CGPointMake(90, 90); // 內容偏移量 sv.pagingEnabled = YES; // 按頁滾動 sv.bounces = YES; // 邊緣彈簧效果 sv.showsVerticalScrollIndicator = NO; // 隱藏滾動條 sv.scrollEnabled = NO; // 禁止滾動
縮放需要實作 viewForZoomingInScrollView: 回傳要縮放的視圖,並設定 maximumZoomScale / minimumZoomScale。要注意滾動與縮放共用同一套手勢,同一個滾動視圖通常只取其一。
無限循環廣告條的思路是:多放一個與首張相同的視圖在末尾,當偏移量到達最後一張時瞬間歸零,視覺上就銜接不上了。
-(void)timer:(NSTimer *)timer {
UIScrollView *sv = (UIScrollView *)[self.view viewWithTag:100];
if (sv.contentOffset.y == 200 * 8) {
sv.contentOffset = CGPointMake(0, 0);
}
[sv setContentOffset:CGPointMake(0, sv.contentOffset.y + 200) animated:YES];
}
UIPageControl 則負責顯示「當前第幾頁」,通常搭配 scrollViewDidScroll: 用 contentOffset.x 除以頁寬來計算頁碼。
表格有 delegate 與 dataSource 兩個代理,其中 numberOfRowsInSection: 與 cellForRowAtIndexPath: 是必須實作的,否則程式會崩潰。
單元格復用是效能關鍵:用 dequeueReusableCellWithIdentifier: 從池中取,池子空了就建立新的,這樣即使一萬筆資料也只會配置約一屏的數量。
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *ID = @"ID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
}
cell.textLabel.text = [dataArray objectAtIndex:indexPath.row];
cell.detailTextLabel.text = @"open";
cell.imageView.image = [UIImage imageNamed:@"5.png"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
其他常用代理方法:numberOfSectionsInTableView: 分組數、heightForRowAtIndexPath: 行高、titleForHeaderInSection: 與 titleForFooterInSection: 組頭組尾標題、didSelectRowAtIndexPath: 處理點擊、sectionIndexTitlesForTableView: 加索引列。
刪除是「資料源與界面」兩步並行,缺一不可:
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
[dataArray removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
}
如果表格分成多段,建議每段各自維護一個陣列,刪除時依 indexPath.section 分派,否則索引錯位很容易崩潰。
自訂 cell 有兩條路:一是建立 xib 並用 loadNibNamed: 載入;二是繼承 UITableViewCell,在 initWithStyle:reuseIdentifier: 中組裝子視圖。要注意 cell 的層次是 cell → contentView → 子控制項,改背景色應該改 contentView。
手寫搜索的關鍵是用 NSPredicate 過濾原陣列,並用一個旗標區分「正在搜索」與「顯示原資料」兩種狀態:
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if (searchBar.text.length == 0) {
isSearch = NO;
[_tableView reloadData];
return;
}
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@", searchBar.text];
self.searchArray = [dataArray filteredArrayUsingPredicate:predicate];
isSearch = YES;
[_tableView reloadData];
}
若使用 UISearchDisplayController,只需實作 shouldReloadTableForSearchString: 並回傳 YES,系統會自動刷新結果列表;此時可透過 tableView.tag 判斷當前刷新的是主表還是結果表。
鍵盤彈起會遮住輸入框,解法是監聽鍵盤通知,在動畫區塊中把整個 view 上移鍵盤高度:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification object:nil];
-(void)keyboardWillShow:(NSNotification *)noti {
NSDictionary *dic = [noti userInfo];
CGRect rect = [[dic objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
float h = rect.size.height;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.25];
self.view.frame = CGRectMake(0, 20 - h, 320, 460);
[UIView commitAnimations];
}
收起鍵盤呼叫 [textField resignFirstResponder],通常掛在 touchesBegan: 裡,點空白處即可收面板。
資料庫操作的四步套路:開啟 → 建立 SQL 語句 → 執行 → 關閉。使用 sqlite3 前需匯入 libsqlite3 並引入 sqlite3.h,檔案路徑建議放在 Documents 目錄:
self.PATH = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
stringByAppendingPathComponent:@"data.db"];
常用 SQL:create table if not exists、insert into、delete from ... where、update ... set ... where、select ... order by ... desc limit、join ... on、count(*)。查詢需要 sqlite3_prepare_v2 建立預處理,再用 sqlite3_step 逐列取出。
FMDB 把上述流程包成 Objective-C 介面,語意直觀得多:
FMDatabase *db = [FMDatabase databaseWithPath:PATH];
if (![db open]) { return; }
[db executeUpdate:@"create table if not exists Students (name, score)"];
[db executeUpdate:@"insert into Students values(?,?)", nameField.text, scoreField.text];
FMResultSet *set = [db executeQuery:@"select * from Students"];
while ([set next]) {
NSString *name = [set stringForColumn:@"name"];
NSString *score = [set stringForColumnIndex:1];
}
[db close];
用 ? 佔位符傳参能避免拼接字串造成的 SQL 注入與引號錯誤,是必須養成的習慣。若要存圖片等非基本型別,可先轉成 NSData,或用 NSKeyedArchiver / NSKeyedUnarchiver 做編碼與解碼。
最簡單的開啟方式是 detachNewThreadSelector,任務寫在被呼叫的方法裡,完成後切回主線程更新 UI:
[NSThread detachNewThreadSelector:@selector(thread) toTarget:self withObject:nil];
-(void)thread {
// 耗時任務...
[self performSelectorOnMainThread:@selector(main1) withObject:nil waitUntilDone:NO];
}
NSTimer 也會開辟執行緒,因此在網路與資料庫場景中,計時器常被用來替代手動開線程。而 GCD 與 NSOperationQueue 則是更現代的選擇,能自動管理執行緒池。
JSON 在字串中以大括號表示字典、中括號表示陣列,解析時只要判斷層次就能對應取值。以 SBJson 為例:
NSDictionary *dic = [json JSONValue]; NSString *str = [dic objectForKey:@"title"];
XML 解析常用 GDataXML,需要額外連結 libxml2 並設定 Header Search Paths。取得節點的手段有 childAtIndex:、elementsForName:、attributes 與 XPath:
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithXMLString:xmlstr options:0 error:nil];
NSArray *users = [doc nodesForXPath:@"//user" error:nil]; // XPath 一律回傳陣列
for (GDataXMLElement *element in users) {
NSString *uid = [[element elementsForName:@"uid"] lastObject].stringValue;
}
非同步下載用 NSURLConnection,四個回呼分別對應:收到回應、持續接收資料、載入完成、發生錯誤:
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self];
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[data1 appendData:data]; // 資料是分次送來的,必須累加
}
SDWebImage 則把「下載 + 快取 + 解碼」一次搞定,一行 setImageWithURL: 即可,且內建記憶體與磁碟兩級快取。
上傳時,ASIFormDataRequest 提供兩種語意不同的介面:setFile:forKey: 只傳檔案內容,而 setFile:withFileName:andContentType:forKey: 會一併告知伺服器檔名與型別,後者在伺服器端才能正確顯示縮圖。
音訊用 AVAudioPlayer,記得先 prepareToPlay 預載,並透過 meteringEnabled 與 updateMeters 取得音量波形:
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"withyou" ofType:@"mp3"]]; player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil]; [player prepareToPlay]; player.currentTime = player.duration * slider.value; // 拖拉進度 player.volume = slider.value; // 音量 player.pan = slider.value; // 聲道 player.rate = slider.value; // 播放速率(需先 enableRate = YES)
影片用 MPMoviePlayerController,注意它與 MPMoviePlayerViewController 的差別:前者需要自己把 view 加進層級並呼叫 play,後者可直接 present 出來以全螢幕播放。
所有繪圖都寫在自訂 UIView 的 drawRect: 中,核心流程是「取得畫紙 → 描述路徑 → 設定樣式 → 描邊或填充」:
CGContextRef ref = UIGraphicsGetCurrentContext(); CGContextMoveToPoint(ref, 20, 100); CGContextAddLineToPoint(ref, 300, 100); CGContextSetStrokeColorWithColor(ref, [UIColor blueColor].CGColor); CGContextSetLineWidth(ref, 20.0); CGContextStrokePath(ref);
三個收尾方法的差別很重要:CGContextStrokePath 只畫輪廓、CGContextFillPath 只填內部、CGContextDrawPath(ref, kCGPathFillStroke) 兩者都畫。
其他常用:CGContextAddRect 畫矩形、CGContextAddEllipseInRect 畫橢圓、CGContextAddArc 畫弧(參數依序為圓心 x、y、半徑、起始角、結束角、順時針旗標,角度用弧度)、CGContextAddQuadCurveToPoint 畫貝茲曲線、CGContextSetLineDash 畫虛線、CGContextSetAlpha 設定透明度、CGContextSetShadow 設定陰影。
最直覺的是 UIView 動畫區塊,把「屬性的新狀態」寫在 begin 與 commit 之間即可:
[UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.3]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; view.frame = CGRectMake(0, 0, 200, 200); [UIView commitAnimations];
需要轉場效果時改用 CATransition(記得引入 QuartzCore),常見 type 有 pageCurl、rippleEffect、suckEffect、cube、oglFlip,再用 subtype 指定方向:
CATransition *trans = [CATransition animation]; trans.duration = 1.0; trans.type = @"rippleEffect"; trans.subtype = kCATransitionFromTop; [self.view.layer addAnimation:trans forKey:nil];
CATransition 只能加在 layer 上,所以切換控制器時要寫成 [self.navigationController.view.layer addAnimation:trans forKey:nil]。
定位與地圖需要 CoreLocation 與 MapKit 兩個框架。地圖顯示位置由 coordinate 與 span 決定,span 越小越精確;定位精度越高越耗電,distanceFilter 則控制位置更新頻率。
MKCoordinateRegion region = MKCoordinateRegionMake(coordinate, MKCoordinateSpanMake(0.5, 0.5)); map.region = region; localManager.desiredAccuracy = kCLLocationAccuracyBest; localManager.distanceFilter = 100; // 移動 100 公尺才更新 [localManager startUpdatingLocation];
大頭針需要一個遵循 MKAnnotation 協議的模型物件,實作 title、subtitle、coordinate 三個方法;渲染時同樣使用 dequeueReusableAnnotationViewWithIdentifier: 做復用,並記得排除系統的 userLocation:
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id)annotation {
if ([annotation isKindOfClass:[mapView.userLocation class]]) { return nil; }
MKPinAnnotationView *pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"ID"];
if (pinView == nil) {
pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"ID"];
}
pinView.canShowCallout = YES;
pinView.animatesDrop = YES;
return pinView;
}
長按落針的實作要記得判斷手勢狀態,只在 UIGestureRecognizerStateBegan 時建立,否則手指不動也會持續產生大頭針。
TCP 面向連線、可靠。伺服器端流程:建立伺服器 socket → acceptOnPort 監聽 → 在 didAcceptNewSocket 中取得新連線 → 呼叫 readDataWithTimeout:-1 tag: 等待資料 → 在 didReadData 中處理並再次發起讀取,形成迴圈。客戶端則是 createClient → connectToHost:onPort: → 在 didConnectToHost 中把連線旗標設為 YES → writeData 送出資料。
[serverSocket acceptOnPort:0x1234 error:nil]; // 伺服器在 0x1234 埠等待連線
- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket {
[newSocket readDataWithTimeout:-1 tag:100]; // -1 表示無限等待
}
UDP 無連線概念,接收端 bindToPort 綁定位埠後 receiveWithTimeout 等待資料,發送端則直接 sendData:toHost:port:。要注意 timeout 只是「告訴系統等多久」,回呼函式本身不會阻塞當前線程。timeout 傳 -1 表示無限等待。
若要在自訂協議中同時傳文字、圖片與語音,實務做法是自訂封包格式:type 表示主類別、subtype 表示子類別、len 表示後續內容長度,接收端依序解析即可。
MRC 時代的三條鐵律:
· 屬性宣告 NSString 用 copy,@synthesize 時加上底線前綴;
· 聲明一次 strong / retain,就要在 dealloc 中對應 release 一次;
· 成員變數釋放的順序是「先 release,再置 nil」,而 property 可以直接 self.xxx = nil。
@property (nonatomic, copy) NSString *descrition;
@synthesize descrition = _descrition;
- (void)dealloc {
[_dict release];
_dict = nil;
[super dealloc];
}
ARC 之下則相反:不需要也不應該呼叫 release、autorelease 與 [super dealloc],strong 相當於 retain、weak 相當於 assign 且不會延長物件生命週期。基本整數型別用 assign 即可,因為它們不涉及物件與引用計數。
Cocos2d 有 oc、c++(cocos2d-x)、java、html5 等多個移植版本。它的心智模型很像電影:一個 CCDirector(導演)、一個運行中的 CCScene(舞臺),每個介面就是一個節目,節目裡再掛 CCSprite(精靈,相當於 UI 中的圖片)與 CCLayer(層)。
BOOL ret = [CCDirector setDirectorType:kCCDirectorTypeDisplayLink]; CCDirector *director = [CCDirector sharedDirector]; [director setDeviceOrientation:kCCDeviceOrientationLandscapeLeft]; [director setOpenGLView:glView]; [director setAnimationInterval:1/60.0f]; [director runWithScene:[StartLayer scene]];
切換場景用 [director replaceScene:],它會自動釋放舊場景,比手動管理記憶體安全得多。精靈的 anchorPoint 是基準點,position 是它在父節點中的位置,兩者搭配才能精準排版。
遊戲邏輯通常掛在 schedule 上週期執行,例如每秒產生敵機、每幀檢查碰撞:
[self schedule:@selector(gameLogic)]; // 預設每 1/60 秒呼叫一次
[self schedule:@selector(addTarget) interval:1.0f]; // 自訂間隔
CGFloat lon = ccpDistance(bullet.position, target.position);
if (lon <= max) { /* 命中,回收物件 */ }
動作系統(CCMoveTo、CCJumpTo、CCCallFuncN)可以串成 CCSequence 讓精靈依序執行,常用來做移動 + 收尾清理的組合。要注意精靈從父節點移除時,必須同步從紀管用於碰撞判斷的陣列中移出,否則會殘留無效引用。
遊戲開發中,物件生命週期管理比一般 App 更吃緊——場景物件多、建立頻繁,任何一處漏掉釋放都會迅速累積成嚴重的記憶體問題。