iPhone 開發的小技巧

1 亂數的使用

標頭檔

#import

#import


srandom()
的使用
srandom((unsigned)(mach_absolute_time() & 0xFFFFFFFF));

直接使用 random() 來調用亂數

2 在UIImageView 中旋轉圖片

float rotateAngle = M_PI;
CGAffineTransform transform =CGAffineTransformMakeRotation(rotateAngle);
imageView.transform = transform;
以上程式旋轉imageView,角度為rotateAngle,方向可以自己測試唷!

3 在Quartz中如何設定旋轉點

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bg.png"]];
imageView.layer.anchorPoint = CGPointMake(0.5, 1.0);


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

4 創建.plist文件並儲存

NSString *errorDesc; //用來存放錯誤訊息用
NSMutableDictionary *rootObj = [NSMutableDictionary dictionaryWithCapacity:4]; //NSDictionary, NSData等文件可以直接賺喚為plist文件

NSDictionary *innerDict;
NSString *name;
Player *player;
NSInteger saveIndex;

for(int i = 0; i < [playerArray count]; i++) { player = nil; player = [playerArray objectAtIndex:i]; if(player == nil) break; name = player.playerName;// This "Player1" denotes the player name could also be the computer name innerDict = [self getAllNodeInfoToDictionary:player]; [rootObj setObject:innerDict forKey:name]; // This "Player1" denotes the person who start this game } player = nil;

NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:(id)rootObj format:NSPropertyListXMLFormat_v1_0 errorDescription:&errorDesc];

红色部分可以忽略,只是给rootObj添加一点内容。這個plistData為創建好的plist文件,用其writeToFile方法就可以寫成文件。下面是代码


/*得到移動設備上的文件存放位置*/
NSString *documentsPath = [self getDocumentsDirectory];
NSString *savePath = [documentsPath stringByAppendingPathComponent:@"save.plist"];

/*存文件*/
if (plistData) {
[plistData writeToFile:savePath atomically:YES];
}
else {
NSLog(errorDesc);
[errorDesc release];
}


- (NSString *)getDocumentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [paths objectAtIndex:0];
}


4 讀取plist文件並轉換為NSDictionary

NSString *documentsPath = [self getDocumentsDirectory];
NSString *fullPath = [documentsPath stringByAppendingPathComponent:@"save.plist"];
NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:fullPath];


5 讀取一般性檔案文件

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];
[scanner scanUpToString:@"<" intoString:nil]; [scanner scanString:@"<" intoString:nil]; [scanner scanUpToString:@">" intoString:&stringBetweenBrackets];

NSLog([stringBetweenBrackets description]);
}


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

6 隱藏NavigationBar
[self.navigationController setNavigationBarHidden:YES animated:YES];

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

虹光大成就-密教灌頂(一)