iOS開發常用的代碼(最基礎)

%c一個單一的字符

%d一個十進制整數

%i一個整數

%e, %f, %g一個浮點數

%o一個八進制數

%s一個字符串

%x一個十六進制數

%p一個指針

%n一個等于讀取字符數量的整數

%u一個無符號整數

%[]一個字符集

%%一個精度符號

//一、NSString

/*----------------創建字符串的方法----------------*/

1、創建常量字符串。

NSString *astring = @"This is a String!";

2、創建空字符串,給予賦值。

NSString *astring = [[NSString alloc] init];

astring = @"This is a String!";

NSLog(@"astring:%@",astring);

[astring release];

3、在以上方法中,提升速度:initWithString方法

NSString *astring = [[NSString alloc] initWithString:@"This is a String!"];

NSLog(@"astring:%@",astring);

[astring release];

4、用標準c創建字符串:initWithCString方法

char *Cstring = "This is a String!";

NSString *astring = [[NSString alloc] initWithCString:Cstring];

NSLog(@"astring:%@",astring);

[astring release];

5、創建格式化字符串:占位符(由一個%加一個字符組成)

int i = 1;

int j = 2;

NSString *astring = [[NSString alloc]

initWithString:[NSString stringWithFormat:@"%d.This is %i string!",i,j]];

NSLog(@"astring:%@",astring);

[astring release];

6、創建臨時字符串

NSString *astring;

astring = [NSString stringWithCString:"This is a temporary string"];

NSLog(@"astring:%@",astring);

/*----------------從文件讀取字符串:initWithContentsOfFile方法----------------*/

NSString *path = @"astring.text";

NSString *astring = [[NSString alloc] initWithContentsOfFile:path];

NSLog(@"astring:%@",astring);

[astring release];

/*----------------寫字符串到文件:writeToFile方法----------------*/

NSString *astring = [[NSString alloc] initWithString:@"This is a String!"];

NSLog(@"astring:%@",astring);

NSString *path = @"astring.text";

[astring writeToFile: path atomically: YES];

[astring release];

/*----------------比較兩個字符串----------------*/

用C比較:strcmp函數

char string1[] = "string!";

char string2[] = "string!";

if(strcmp(string1, string2) = = 0)

{

NSLog(@"1");

}

isEqualToString方法

NSString *astring01 = @"This is a String!";

NSString *astring02 = @"This is a String!";

BOOL result = [astring01 isEqualToString:astring02];

NSLog(@"result:%d",result);

compare方法(comparer返回的三種值)

NSString *astring01 = @"This is a String!";

NSString *astring02 = @"This is a String!";

BOOL result = [astring01 compare:astring02] = = NSOrderedSame;

NSLog(@"result:%d",result);

NSOrderedSame判斷兩者內容是否相同

NSString *astring01 = @"This is a String!";

NSString *astring02 = @"this is a String!";

BOOL result = [astring01 compare:astring02] = = NSOrderedAscending;

NSLog(@"result:%d",result);

//NSOrderedAscending判斷兩對象值的大小(按字母順序進行比較,astring02大于astring01為真)

NSString *astring01 = @"this is a String!";

NSString *astring02 = @"This is a String!";

BOOL result = [astring01 compare:astring02] = = NSOrderedDescending;

NSLog(@"result:%d",result);

//NSOrderedDescending判斷兩對象值的大小(按字母順序進行比較,astring02小于astring01為真)

不考慮大 小寫比較字符串1

NSString *astring01 = @"this is a String!";

NSString *astring02 = @"This is a String!";

BOOL result = [astring01 caseInsensitiveCompare:astring02] = = NSOrderedSame;

NSLog(@"result:%d",result);

//NSOrderedDescending判斷兩對象值的大小(按字母順序進行比較,astring02小于astring01為 真)

不考慮大小寫比較字符串2

NSString *astring01 = @"this is a String!";

NSString *astring02 = @"This is a String!";

BOOL result = [astring01 compare:astring02

options:NSCaseInsensitiveSearch | NSNumericSearch] = = NSOrderedSame;

NSLog(@"result:%d",result);

//NSCaseInsensitiveSearch:不區分大小寫比較NSLiteralSearch:進行完全比較,區分大小寫NSNumericSearch:比較字符串的字符個數,而不是字符值。

/*----------------改變字符串的大小寫----------------*/

NSString *string1 = @"A String";

NSString *string2 = @"String";

NSLog(@"string1:%@",[string1 uppercaseString]);//大寫

NSLog(@"string2:%@",[string2 lowercaseString]);//小寫

NSLog(@"string2:%@",[string2 capitalizedString]);//首字母大小

/*----------------在串中搜索子串----------------*/

NSString *string1 = @"This is a string";

NSString *string2 = @"string";

NSRange range = [string1 rangeOfString:string2];

int location = range.location;

int leight = range.length;

NSString *astring = [[NSString alloc]

initWithString:[NSString stringWithFormat:@"Location:%i,Leight:%i"

,location,leight]];

NSLog(@"astring:%@",astring);

[astring release];

/*----------------抽取子串----------------*/

-substringToIndex:從字符串的開頭一直截取到指定的位置,但不包括該位置的字符

NSString *string1 = @"This is a string";

NSString *string2 = [string1 substringToIndex:3];

NSLog(@"string2:%@",string2);

-substringFromIndex:以指定位置開始(包括指定位置的字符),并包括之后的全部字符

NSString *string1 = @"This is a string";

NSString *string2 = [string1 substringFromIndex:3];

NSLog(@"string2:%@",string2);

-substringWithRange: //按照所給出的位置,長度,任意地從字符串中截取子串

NSString *string1 = @"This is a string";

NSString *string2 = [string1 substringWithRange:NSMakeRange(0, 4)];

NSLog(@"string2:%@",string2);

const char *fieldValue = [valuecStringUsingEncoding:NSUTF8StringEncoding];

const char *fieldValue = [value UTF8String];

NSString轉NSData

NSString* str= @"kilonet";

NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];

Date format用法:

-(NSString *) getDay:(NSDate *) d

{

NSString *s ;

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

[format setDateFormat:@"YYYY/MM/dd hh:mm:ss"];

s = [format stringFromDate:d];

[format release];

return s;

}

各地時區獲取:

NSDate *nowDate = [NSDate new];

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

[formattersetDateFormat:@"yyyy/MM/dd HH:mm:ss"];

//根據時區名字獲取當前時間,如果該時區不存在,默認獲取系統當前時區的時間

//NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Europe/Andorra"];

//[formatter setTimeZone:timeZone];

//獲取所有的時區名字

NSArray *array = [NSTimeZone knownTimeZoneNames];

//NSLog(@"array:%@",array);

//for循環

//for(int i=0;i<[array count];i++)

//{

//NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:[array objectAtIndex:i]];

//[formatter setTimeZone:timeZone];

//NSString *locationTime = [formatter stringFromDate:nowDate];

//NSLog(@"時區名字:%@:時區當前時間: %@",[array objectAtIndex:i],locationTime);

////NSLog(@"timezone name is:%@",[array objectAtIndex:i]);

//}

//快速枚舉法

for(NSString *timeZoneName in array){

[formatter setTimeZone:[NSTimeZone timeZoneWithName:timeZoneName]];

NSLog(@"%@,%@",timeZoneName,[formatter stringFromDate:nowDate]);

}

[formatter release];

[nowDate release];

NSCalendar用法:

-(NSString *) getWeek:(NSDate *) d {

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit |NSDayCalendarUnit | NSWeekdayCalendarUnit;

NSDateComponents *components = [calendar components:units fromDate:d];

[calendar release];

switch ([components weekday]) {

case 2:

return @"Monday";

break;

case 3:

return @"Tuesday";

break;

case 4:

return @"Wednesday";

break;

case 5:

return @"Thursday";

break;

case 6:

return@"Friday";

break;

case 7:

return@"Saturday";

break;

case 1:

return @"Sunday";

break;

default:

return @"No Week";

break;

}

//用components,我們可以讀取其他更多的數據。

}

4.用Get方式讀取網絡數據:

將網絡數讀取為字符串

- (NSString *) getDataByURL:(NSString *) url {

return [[NSString alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]] encoding:NSUTF8StringEncoding];

}

//讀取網絡圖片

- (UIImage *) getImageByURL:(NSString *) url {

return [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];

}

多線程

[NSThread detachNewThreadSelector:@selector(scheduleTask) toTarget:self withObject:nil];

-(void) scheduleTask {

//create a pool

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

//release the pool;

[pool release];

}

//如果有參數,則這么使用:

[NSThread detachNewThreadSelector:@selector(scheduleTask:) toTarget:self withObject:[NSDate date]];

-(void) scheduleTask:(NSDate *) mdate {

//create a pool

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

//release the pool;

[pool release];

}

//注意selector里有冒號。

//在線程里運行主線程里的方法

[self performSelectorOnMainThread:@selector(moveToMain) withObject:nil waitUntilDone:FALSE];

6.定時器NSTimer用法:

代碼

//一個可以自動關閉的Alert窗口

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil

message:[@"一個可以自動關閉的Alert窗口"

delegate:nil

cancelButtonTitle:nil //NSLocalizedString(@"OK", @"OK")//取消任何按鈕

otherButtonTitles:nil];

//[alert setBounds:CGRectMake

(alert.bounds.origin.x, alert.bounds.origin.y,

alert.bounds.size.width, alert.bounds.size.height+30.0)];

[alert show];

UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];

// Adjust the indicator so it is up a few pixels from the bottom of the alert

indicator.center = CGPointMake(alert.bounds.size.width/2,alert.bounds.size.height-40.0);

[indicator startAnimating];

[alert insertSubview:indicator atIndex:0];

[indicator release];

[NSTimer scheduledTimerWithTimeInterval:3.0f

target:self

selector:@selector(dismissAlert:)

userInfo:[NSDictionary dictionaryWithObjectsAndKeys:alert,

@"alert", @"testing ", @"key" ,nil]//如果不用傳遞參數,那么可以將此項設置為nil.

repeats:NO];

NSLog(@"release alert");

[alert release];

-(void) dismissAlert:(NSTimer *)timer{

NSLog(@"release timer");

NSLog([[timer userInfo]objectForKey:@"key"]);

UIAlertView *alert = [[timer userInfo]objectForKey:@"alert"];

[alert dismissWithClickedButtonIndex:0 animated:YES];

}

定時器停止使用:

[timer invalidate];

timer = nil;

7.用戶缺省值NSUserDefaults讀取:

//得到用戶缺省值

NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];

//在缺省值中找到AppleLanguages,返回值是一個數組

NSArray* languages = [defs objectForKey:@"AppleLanguages"];

NSLog(@"all language語言is %@", languages);

//在得到的數組中的第一個項就是用戶的首選語言了

NSLog(@"首選語言is %@",[languages objectAtIndex:0]);

//get the language & country code

NSLocale *currentLocale = [NSLocale currentLocale];

NSLog(@"Language Code is %@", [currentLocale objectForKey:NSLocaleLanguageCode]);

NSLog(@"Country Code is %@", [currentLocale objectForKey:NSLocaleCountryCode

8. View之間切換的動態效果設置:

SettingsController *settings = [[SettingsController alloc]initWithNibName:@"SettingsView" bundle:nil];

settings.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;//水平翻轉

[self presentModalViewController:settings animated:YES];

[settings release];

9.NSScrollView滑動用法:

-(void) scrollViewDidScroll:(UIScrollView *)scrollView{

NSLog(@"正在滑動中...");

}

//用戶直接滑動NSScrollView,可以看到滑動條

-(void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

}

//通過其他控件觸發NSScrollView滑動,看不到滑動條

- (void) scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {

}

11.鍵盤處理系列

//set the UIKeyboard to switch to a different text field when you press return

//switch textField to the name of your textfield

[textField becomeFirstResponder];

srandom(time(NULL)); //隨機數種子

id d = random(); //隨機數

4. iPhone的系統目錄:

//得到Document目錄:

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

NSString *documentsDirectory = [paths objectAtIndex:0];

//得到temp臨時目錄:

NSString *tempPath = NSTemporaryDirectory();

//得到目錄上的文件地址:

NSString *文件地址= [目錄地址stringByAppendingPathComponent:@"文件名.擴展名"];

5.狀態欄顯示Indicator:

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

6.app Icon顯示數字:

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

[[UIApplication sharedApplication] setApplicationIconBadgeNumber:5];

}

7.sqlite保存地址:

代碼

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

NSString *thePath = [paths objectAtIndex:0];

NSString *filePath = [thePath stringByAppendingPathComponent:@"kilonet1.sqlite"];

NSString *dbPath = [[[NSBundle mainBundle] resourcePath]

stringByAppendingPathComponent:@"kilonet2.sqlite"];

8.Application退出:exit(0);

9. AlertView,ActionSheet的cancelButton點擊事件:

代碼

-(void) actionSheet :(UIActionSheet *) actionSheet didDismissWithButtonIndex:(NSInteger) buttonIndex {

NSLog(@"cancel actionSheet........");

//當用戶按下cancel按鈕

if( buttonIndex == [actionSheet cancelButtonIndex]) {

exit(0);

}

////當用戶按下destructive按鈕

//if( buttonIndex == [actionSheet destructiveButtonIndex]) {

//// DoSomething here.

//}

}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {

NSLog(@"cancel alertView........");

if (buttonIndex == [alertView cancelButtonIndex]) {

exit(0);

}

}

10.給Window設置全局的背景圖片:

window.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"coolblack.png"]];

11. UITextField文本框顯示及對鍵盤的控制:

代碼

#pragma mark -

#pragma mark UITextFieldDelegate

//控制鍵盤跳轉

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

if (textField == _txtAccount) {

if ([_txtAccount.text length]==0) {

return NO;

}

[_txtPassword becomeFirstResponder];

} else if (textField == _txtPassword) {

[_txtPassword resignFirstResponder];

}

return YES;

}

//輸入框背景更換

-(BOOL) textFieldShouldBeginEditing:(UITextField *)textField{

[textField setBackground:[UIImage imageNamed:@"ctext_field_02.png"]];

return YES;

}

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

[textField setBackground:[UIImage imageNamed:@"ctext_field_01.png"]];

}

12.UITextField文本框前面空白寬度設置以及后面組合按鈕設置:

代碼

//給文本輸入框后面加入空白

_txtAccount.rightView = _btnDropDown;

_txtAccount.rightViewMode =UITextFieldViewModeAlways;

//給文本輸入框前面加入空白

CGRect frame = [_txtAccount frame];

frame.size.width = 5;

UIView *leftview = [[UIView alloc] initWithFrame:frame];

_txtAccount.leftViewMode = UITextFieldViewModeAlways;

_txtAccount.leftView = leftview;

13. UIScrollView設置滑動不超出本身范圍:

[fcScrollView setBounces:NO];

14.在drawRect里畫文字:

UIFont * f = [UIFont systemFontOfSize:20];

[[UIColor darkGrayColor] set];

NSString * text = @"hi \nKiloNet";

[text drawAtPoint:CGPointMake(center.x,center.y) withFont:f];

15. NSArray查找是否存在對象時用indexOfObject,如果不存在則返回為NSNotFound.

16. NString與NSArray之間相互轉換:

array = [string componentsSeparatedByString:@","];

string = [[array valueForKey:@"description"] componentsJoinedByString:@","];

17. TabController隨意切換tab bar:

[self.tabBarController setSelectedIndex:tabIndex];

或者self.tabBarController.selectedIndex = tabIndex;

或者實現下面的delegate來撲捉tab bar的事件:

代碼-(BOOL) tabBarController:(UITabBarController *)tabBarController

shouldSelectViewController:(UIViewController *)viewController

{if ([viewController.tabBarItem.title isEqualToString: NSLocalizedString(@"Logout",nil)])

{[self showLogout];return NO;}return YES;}

18.自定義View之間切換動畫:

代碼

- (void) pushController: (UIViewController*) controller

withTransition: (UIViewAnimationTransition) transition

{

[UIView beginAnimations:nil context:NULL];

[self pushViewController:controller animated:NO];

[UIView setAnimationDuration:.5];

[UIView setAnimationBeginsFromCurrentState:YES];

[UIView setAnimationTransition:transition forView:self.view cache:YES];

[UIView commitAnimations];

}

CATransition *transition = [CATransition animation];

transition.duration = kAnimationDuration;

transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

transition.type = kCATransitionPush;

transition.subtype = kCATransitionFromTop;

transitioning = YES;

transition.delegate = self;

[self.navigationController.view.layer addAnimation:transition forKey:nil];

self.navigationController.navigationBarHidden = NO;

[self.navigationController pushViewController:tableViewController animated:YES];

20.計算字符串長度:

CGFloat w = [title sizeWithFont:[UIFont fontWithName:@"Arial" size:18]].width;

23.在使用UISearchBar時,將背景色設定為clearColor,或者將translucent設為YES,都不能使背景透明,經過一番研究,發現了一種超級簡單和實用的方法:

1

[[searchbar.subviews objectAtIndex:0]removeFromSuperview];

背景完全消除了,只剩下搜索框本身了。

24.圖像與緩存:

UIImageView *wallpaper = [[UIImageView alloc] initWithImage:

[UIImage imageNamed:@"icon.png"]]; //會緩存圖片

UIImageView *wallpaper = [[UIImageView alloc] initWithImage:

[UIImage imageWithContentsOfFile:@"icon.png"]]; //不會緩存圖片

25. iphone-常用的對視圖圖層(layer)的操作

對圖層的操作:

(1.給圖層添加背景圖片:

myView.layer.contents = (id)[UIImage imageNamed:@"view_BG.png"].CGImage;

(2.將圖層的邊框設置為圓腳

myWebView.layer.cornerRadius = 8;

myWebView.layer.masksToBounds = YES;

(3.給圖層添加一個有色邊框

myWebView.layer.borderWidth = 5;

myWebView.layer.borderColor = [[UIColor colorWithRed:0.52 green:0.09 blue:0.07 alpha:1] CGColor];

將多個字符替換成空

NSCharacterSet *cs = [NSCharacterSet characterSetWithCharactersInString:@"1234567890|"];

NSString *resultstr = [[yourstr componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@" "];

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,431評論 6 544
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,637評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,555評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,900評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,629評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,976評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,976評論 3 448
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,139評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,686評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,411評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,641評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,129評論 5 364
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,820評論 3 350
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,233評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,567評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,362評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,604評論 2 380

推薦閱讀更多精彩內容