iOS 知識-經常使用小技巧大雜燴

原文連接:http://www.jianshu.com/p/7c3ee5e67d03。javascript

本身看的。css

1,打印View全部子視圖java

po [[self view]recursiveDescription]

2,layoutSubviews調用的調用時機ios

* 當視圖第一次顯示的時候會被調用 * 當這個視圖顯示到屏幕上了,點擊按鈕 * 添加子視圖也會調用這個方法 * 當本視圖的大小發生改變的時候是會調用的 * 當子視圖的frame發生改變的時候是會調用的 * 當刪除子視圖的時候是會調用的

3,NSString過濾特殊字符git

// 定義一個特殊字符的集合 NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString: @"@/:;()¥「」"、[]{}#%-*+=_\\|~<>$€^•'@#$%^&*()_+'\""]; // 過濾字符串的特殊字符 NSString *newString = [trimString stringByTrimmingCharactersInSet:set];

4,TransForm屬性github

//平移按鈕 CGAffineTransform transForm = self.buttonView.transform; self.buttonView.transform = CGAffineTransformTranslate(transForm, 10, 0); //旋轉按鈕 CGAffineTransform transForm = self.buttonView.transform; self.buttonView.transform = CGAffineTransformRotate(transForm, M_PI_4); //縮放按鈕 self.buttonView.transform = CGAffineTransformScale(transForm, 1.2, 1.2); //初始化復位 self.buttonView.transform = CGAffineTransformIdentity;

5,去掉分割線多餘15像素sql

首先在viewDidLoad方法加入如下代碼:
 if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) { [self.tableView setSeparatorInset:UIEdgeInsetsZero]; } if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) { [self.tableView setLayoutMargins:UIEdgeInsetsZero]; } 而後在重寫willDisplayCell方法 - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{ if ([cell respondsToSelector:@selector(setSeparatorInset:)]) { [cell setSeparatorInset:UIEdgeInsetsZero]; } if ([cell respondsToSelector:@selector(setLayoutMargins:)]) { [cell setLayoutMargins:UIEdgeInsetsZero]; } }

6,計算方法耗時時間間隔xcode

// 獲取時間間隔 #define TICK CFAbsoluteTime start = CFAbsoluteTimeGetCurrent(); #define TOCK NSLog(@"Time: %f", CFAbsoluteTimeGetCurrent() - start)

7,Color顏色宏定義緩存

// 隨機顏色 #define RANDOM_COLOR [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1] // 顏色(RGB) #define RGBCOLOR(r, g, b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1] // 利用這種方法設置顏色和透明值,可不影響子視圖背景色 #define RGBACOLOR(r, g, b, a) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:(a)]

8,Alert提示宏定義bash

#define Alert(_S_, ...) [[[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:(_S_), ##__VA_ARGS__] delegate:nil cancelButtonTitle:@"肯定" otherButtonTitles:nil] show]

8,讓 iOS 應用直接退出

- (void)exitApplication { AppDelegate *app = [UIApplication sharedApplication].delegate; UIWindow *window = app.window; [UIView animateWithDuration:1.0f animations:^{ window.alpha = 0; } completion:^(BOOL finished) { exit(0); }]; }

8,NSArray 快速求總和 最大值 最小值 和 平均值

NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil]; CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue]; CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue]; CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue]; CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue]; NSLog(@"%f\n%f\n%f\n%f",sum,avg,max,min);

9,修改Label中不一樣文字顏色

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self editStringColor:self.label.text editStr:@"好" color:[UIColor blueColor]]; } - (void)editStringColor:(NSString *)string editStr:(NSString *)editStr color:(UIColor *)color { // string爲總體字符串, editStr爲須要修改的字符串 NSRange range = [string rangeOfString:editStr]; NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:string]; // 設置屬性修改字體顏色UIColor與大小UIFont [attribute addAttributes:@{NSForegroundColorAttributeName:color} range:range]; self.label.attributedText = attribute; }

10,播放聲音

#import<AVFoundation/AVFoundation.h> // 1.獲取音效資源的路徑 NSString *path = [[NSBundle mainBundle]pathForResource:@"pour_milk" ofType:@"wav"]; // 2.將路勁轉化爲url NSURL *tempUrl = [NSURL fileURLWithPath:path]; // 3.用轉化成的url建立一個播放器 NSError *error = nil; AVAudioPlayer *play = [[AVAudioPlayer alloc]initWithContentsOfURL:tempUrl error:&error]; self.player = play; // 4.播放 [play play];

11,檢測是否IPad Pro和其它設備型號

- (BOOL)isIpadPro
{   
  UIScreen *Screen = [UIScreen mainScreen];   
  CGFloat width = Screen.nativeBounds.size.width/Screen.nativeScale;  
  CGFloat height = Screen.nativeBounds.size.height/Screen.nativeScale;         
  BOOL isIpad =[[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad;   
  BOOL hasIPadProWidth = fabs(width - 1024.f) < DBL_EPSILON; BOOL hasIPadProHeight = fabs(height - 1366.f) < DBL_EPSILON; return isIpad && hasIPadProHeight && hasIPadProWidth; } #define UI_IS_LANDSCAPE ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft || [UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeRight)#define UI_IS_IPAD ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)#define UI_IS_IPHONE ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)#define UI_IS_IPHONE4 (UI_IS_IPHONE && [[UIScreen mainScreen] bounds].size.height < 568.0)#define UI_IS_IPHONE5 (UI_IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 568.0)#define UI_IS_IPHONE6 (UI_IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 667.0)#define UI_IS_IPHONE6PLUS (UI_IS_IPHONE && [[UIScreen mainScreen] bounds].size.height == 736.0 || [[UIScreen mainScreen] bounds].size.width == 736.0) // Both orientations#define UI_IS_IOS8_AND_HIGHER ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) 文/Originalee(簡書做者)原文連接:http://www.jianshu.com/p/9d36aa12429f著做權歸做者全部,轉載請聯繫做者得到受權,並標註「簡書做者」。

11,修改Tabbar Item的屬性

// 修改標題位置 self.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, -10); // 修改圖片位置 self.tabBarItem.imageInsets = UIEdgeInsetsMake(-3, 0, 3, 0); // 批量修改屬性 for (UIBarItem *item in self.tabBarController.tabBar.items) { [item setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIFont fontWithName:@"Helvetica" size:19.0], NSFontAttributeName, nil] forState:UIControlStateNormal]; } // 設置選中和未選中字體顏色 [[UITabBar appearance] setShadowImage:[[UIImage alloc] init]]; //未選中字體顏色 [[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor greenColor]} forState:UIControlStateNormal]; //選中字體顏色 [[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor cyanColor]} forState:UIControlStateSelected];

12,NULL - nil - Nil - NSNULL的區別

* nil是OC的,空對象,地址指向空(0)的對象。對象的字面零值 * Nil是Objective-C類的字面零值 * NULL是C的,空地址,地址的數值是0,是個長整數 * NSNull用於解決向NSArray和NSDictionary等集合中添加空值的問題

11,去掉BackBarButtonItem的文字

[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];

12,控件不能交互的一些緣由

1,控件的userInteractionEnabled = NO 2,透明度小於等於0.01,aplpha 3,控件被隱藏的時候,hidden = YES 4,子視圖的位置超出了父視圖的有效範圍,子視圖沒法交互,設置了。 5,須要交互的視圖,被其餘視圖蓋住(其餘視圖開啓了用戶交互)。

12,修改UITextField中Placeholder的文字顏色

[text setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"]; }

13,視圖的生命週期

一、 alloc 建立對象,分配空間 二、 init (initWithNibName) 初始化對象,初始化數據 三、 loadView 從nib載入視圖 ,除非你沒有使用xib文件建立視圖 四、 viewDidLoad 載入完成,能夠進行自定義數據以及動態建立其餘控件 五、 viewWillAppear視圖將出如今屏幕以前,立刻這個視圖就會被展示在屏幕上了 六、 viewDidAppear 視圖已在屏幕上渲染完成 一、viewWillDisappear 視圖將被從屏幕上移除以前執行 二、viewDidDisappear 視圖已經被從屏幕上移除,用戶看不到這個視圖了 三、dealloc 視圖被銷燬,此處須要對你在init和viewDidLoad中建立的對象進行釋放. viewVillUnload- 當內存太低,即將釋放時調用; viewDidUnload-當內存太低,釋放一些不須要的視圖時調用。

14,應用程序的生命週期

1,啓動但還沒進入狀態保存 : - (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions 2,基本完成程序準備開始運行: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 3,當應用程序將要入非活動狀態執行,應用程序不接收消息或事件,好比來電話了: - (void)applicationWillResignActive:(UIApplication *)application 4,當應用程序入活動狀態執行,這個恰好跟上面那個方法相反: - (void)applicationDidBecomeActive:(UIApplication *)application 5,當程序被推送到後臺的時候調用。因此要設置後臺繼續運行,則在這個函數裏面設置便可: - (void)applicationDidEnterBackground:(UIApplication *)application 6,當程序從後臺將要從新回到前臺時候調用,這個恰好跟上面的那個方法相反: - (void)applicationWillEnterForeground:(UIApplication *)application 7,當程序將要退出是被調用,一般是用來保存數據和一些退出前的清理工做: - (void)applicationWillTerminate:(UIApplication *)application

15,判斷view是否是指定視圖的子視圖

BOOL isView = [textView isDescendantOfView:self.view];

16,判斷對象是否遵循了某協議

if ([self.selectedController conformsToProtocol:@protocol(RefreshPtotocol)]) { [self.selectedController performSelector:@selector(onTriggerRefresh)]; }

17,頁面強制橫屏

#pragma mark - 強制橫屏代碼 - (BOOL)shouldAutorotate{ //是否支持轉屏 return NO; } - (UIInterfaceOrientationMask)supportedInterfaceOrientations{ //支持哪些轉屏方向 return UIInterfaceOrientationMaskLandscape; } - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{ return UIInterfaceOrientationLandscapeRight; } - (BOOL)prefersStatusBarHidden{ return NO; }

18,系統鍵盤通知消息

一、UIKeyboardWillShowNotification-將要彈出鍵盤 二、UIKeyboardDidShowNotification-顯示鍵盤 三、UIKeyboardWillHideNotification-將要隱藏鍵盤 四、UIKeyboardDidHideNotification-鍵盤已經隱藏 五、UIKeyboardWillChangeFrameNotification-鍵盤將要改變frame 六、UIKeyboardDidChangeFrameNotification-鍵盤已經改變frame

19,關閉navigationController的滑動返回手勢

self.navigationController.interactivePopGestureRecognizer.enabled = NO;

20,設置狀態欄背景爲任意的顏色

- (void)setStatusColor { UIView *statusBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, 20)]; statusBarView.backgroundColor = [UIColor orangeColor]; [self.view addSubview:statusBarView]; }

21,讓Xcode的控制檯支持LLDB類型的打印

打開終端輸入三條命令:
    touch ~/.lldbinit
    echo display @import UIKit >> ~/.lldbinit echo target stop-hook add -o \"target stop-hook disable\" >> ~/.lldbinit

下次從新運行項目,而後就不報錯了。


 


22,Label行間距

-(void)test{ NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:self.contentLabel.text]; NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; [paragraphStyle setLineSpacing:3]; //調整行間距 [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [self.contentLabel.text length])]; self.contentLabel.attributedText = attributedString; }

23,UIImageView填充模式

@"UIViewContentModeScaleToFill", // 拉伸自適應填滿整個視圖 @"UIViewContentModeScaleAspectFit", // 自適應比例大小顯示 @"UIViewContentModeScaleAspectFill", // 原始大小顯示 @"UIViewContentModeRedraw", // 尺寸改變時重繪 @"UIViewContentModeCenter", // 中間 @"UIViewContentModeTop", // 頂部 @"UIViewContentModeBottom", // 底部 @"UIViewContentModeLeft", // 中間貼左 @"UIViewContentModeRight", // 中間貼右 @"UIViewContentModeTopLeft", // 貼左上 @"UIViewContentModeTopRight", // 貼右上 @"UIViewContentModeBottomLeft", // 貼左下 @"UIViewContentModeBottomRight", // 貼右下

24,宏定義檢測block是否可用

#define BLOCK_EXEC(block, ...) if (block) { block(__VA_ARGS__); }; // 宏定義以前的用法 if (completionBlock) { completionBlock(arg1, arg2); } // 宏定義以後的用法 BLOCK_EXEC(completionBlock, arg1, arg2);

25,Debug欄打印時自動把Unicode編碼轉化成漢字

// 有時候咱們在xcode中打印中文,會打印出Unicode編碼,還須要本身去一些在線網站轉換,有了插件就方便多了。 DXXcodeConsoleUnicodePlugin 插件

26,設置狀態欄文字樣式顏色

[[UIApplication sharedApplication] setStatusBarHidden:NO]; [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

26,自動生成模型代碼的插件

// 可自動生成模型的代碼,省去寫模型代碼的時間 ESJsonFormat-for-Xcode

27,iOS中的一些手勢

輕擊手勢(TapGestureRecognizer)
輕掃手勢(SwipeGestureRecognizer)
長按手勢(LongPressGestureRecognizer)
拖動手勢(PanGestureRecognizer)
捏合手勢(PinchGestureRecognizer)
旋轉手勢(RotationGestureRecognizer)

27,iOS 開發中一些相關的路徑

模擬器的位置:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs 文檔安裝位置: /Applications/Xcode.app/Contents/Developer/Documentation/DocSets 插件保存路徑: ~/Library/ApplicationSupport/Developer/Shared/Xcode/Plug-ins 自定義代碼段的保存路徑: ~/Library/Developer/Xcode/UserData/CodeSnippets/ 若是找不到CodeSnippets文件夾,能夠本身新建一個CodeSnippets文件夾。 證書路徑 ~/Library/MobileDevice/Provisioning Profiles

28,獲取 iOS 路徑的方法

獲取家目錄路徑的函數
NSString *homeDir = NSHomeDirectory(); 獲取Documents目錄路徑的方法 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *docDir = [paths objectAtIndex:0]; 獲取Documents目錄路徑的方法 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *cachesDir = [paths objectAtIndex:0]; 獲取tmp目錄路徑的方法: NSString *tmpDir = NSTemporaryDirectory();

29,字符串相關操做

去除全部的空格
[str stringByReplacingOccurrencesOfString:@" " withString:@""] 去除首尾的空格 [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; - (NSString *)uppercaseString; 所有字符轉爲大寫字母 - (NSString *)lowercaseString 所有字符轉爲小寫字母

30, CocoaPods pod install/pod update更新慢的問題

pod install --verbose --no-repo-update pod update --verbose --no-repo-update 若是不加後面的參數,默認會升級CocoaPods的spec倉庫,加一個參數能夠省略這一步,而後速度就會提高很多。

31,MRC和ARC混編設置方式

在XCode中targets的build phases選項下Compile Sources下選擇 不須要arc編譯的文件 雙擊輸入 -fno-objc-arc 便可 MRC工程中也可使用ARC的類,方法以下: 在XCode中targets的build phases選項下Compile Sources下選擇要使用arc編譯的文件 雙擊輸入 -fobjc-arc 便可

32,把tableview裏cell的小對勾的顏色改爲別的顏色

_mTableView.tintColor = [UIColor redColor];

33,調整tableview的separaLine線的位置

tableView.separatorInset = UIEdgeInsetsMake(0, 100, 0, 0);

34,設置滑動的時候隱藏navigationbar

navigationController.hidesBarsOnSwipe = Yes

35,自動處理鍵盤事件,實現輸入框防遮擋的插件

IQKeyboardManager
https://github.com/hackiftekhar/IQKeyboardManager

36,Quartz2D相關

圖形上下是一個CGContextRef類型的數據。
圖形上下文包含:
1,繪圖路徑(各類各樣圖形) 2,繪圖狀態(顏色,線寬,樣式,旋轉,縮放,平移) 3,輸出目標(繪製到什麼地方去?UIView、圖片) 1,獲取當前圖形上下文 CGContextRef ctx = UIGraphicsGetCurrentContext(); 2,添加線條 CGContextMoveToPoint(ctx, 20, 20); 3,渲染 CGContextStrokePath(ctx); CGContextFillPath(ctx); 4,關閉路徑 CGContextClosePath(ctx); 5,畫矩形 CGContextAddRect(ctx, CGRectMake(20, 20, 100, 120)); 6,設置線條顏色 [[UIColor redColor] setStroke]; 7, 設置線條寬度 CGContextSetLineWidth(ctx, 20); 8,設置頭尾樣式 CGContextSetLineCap(ctx, kCGLineCapSquare); 9,設置轉折點樣式 CGContextSetLineJoin(ctx, kCGLineJoinBevel); 10,畫圓 CGContextAddEllipseInRect(ctx, CGRectMake(30, 50, 100, 100)); 11,指定圓心 CGContextAddArc(ctx, 100, 100, 50, 0, M_PI * 2, 1); 12,獲取圖片上下文 UIGraphicsGetImageFromCurrentImageContext(); 13,保存圖形上下文 CGContextSaveGState(ctx) 14,恢復圖形上下文 CGContextRestoreGState(ctx)

37,屏幕截圖

// 1. 開啓一個與圖片相關的圖形上下文 UIGraphicsBeginImageContextWithOptions(self.view.bounds.size,NO,0.0); // 2. 獲取當前圖形上下文 CGContextRef ctx = UIGraphicsGetCurrentContext(); // 3. 獲取須要截取的view的layer [self.view.layer renderInContext:ctx]; // 4. 從當前上下文中獲取圖片 UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); // 5. 關閉圖形上下文 UIGraphicsEndImageContext(); // 6. 把圖片保存到相冊 UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

37,左右抖動動畫

//1, 建立核心動畫 CAKeyframeAnimation *keyAnima = [CAKeyframeAnimation animation]; //2, 告訴系統執行什麼動畫。 keyAnima.keyPath = @"transform.rotation"; keyAnima.values = @[@(-M_PI_4 /90.0 * 5),@(M_PI_4 /90.0 * 5),@(-M_PI_4 /90.0 * 5)]; // 3, 執行完以後不刪除動畫 keyAnima.removedOnCompletion = NO; // 4, 執行完以後保存最新的狀態 keyAnima.fillMode = kCAFillModeForwards; // 5, 動畫執行時間 keyAnima.duration = 0.2; // 6, 設置重複次數。 keyAnima.repeatCount = MAXFLOAT; // 7, 添加核心動畫 [self.iconView.layer addAnimation:keyAnima forKey:nil];

38,CALayer 的知識

CALayer 負責視圖中顯示內容和動畫 UIView 負責監聽和響應事件 建立UIView對象時,UIView內部會自動建立一個圖層(既CALayer) UIView自己不具有顯示的功能,是它內部的層纔有顯示功能. CALayer屬性: position 中點(由anchorPoint決定) anchorPoint 錨點 borderColor 邊框顏色 borderWidth 邊框寬度 cornerRadius 圓角半徑 shadowColor 陰影顏色 contents 內容 opacity 透明度 shadowOpacity 偏移 shadowRadius 陰影半徑 shadowColor 陰影顏色 masksToBounds 裁剪

39,性能相關

1. 視圖複用,好比UITableViewCell,UICollectionViewCell. 2. 數據緩存,好比用SDWebImage實現圖片緩存。 3. 任何狀況下都不能堵塞主線程,把耗時操做盡可能放到子線程。 4. 若是有多個下載同時併發,能夠控制併發數。 5. 在合適的地方儘可能使用懶加載。 6. 重用重大開銷對象,好比:NSDateFormatter、NSCalendar。 7. 選擇合適的數據存儲。 8. 避免循環引用。避免delegate用retain、strong修飾,block可能致使循環引用,NSTimer也可能致使內存泄露等。 9. 當涉及到定位的時候,不用的時候最好把定位服務關閉。由於定位耗電、流量。 10. 加鎖對性能有重大開銷。 11. 界面最好不要添加過多的subViews. 12. TableView 若是不一樣行高,那麼返回行高,最好作緩存。 13. Viewdidload 裏儘可能不要作耗時操做。

40,驗證身份證號碼

//驗證身份證號碼 - (BOOL)checkIdentityCardNo:(NSString*)cardNo { if (cardNo.length != 18) { return NO; } NSArray* codeArray = [NSArray arrayWithObjects:@"7",@"9",@"10",@"5",@"8",@"4",@"2",@"1",@"6",@"3",@"7",@"9",@"10",@"5",@"8",@"4",@"2", nil]; NSDictionary* checkCodeDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1",@"0",@"X",@"9",@"8",@"7",@"6",@"5",@"4",@"3",@"2", nil] forKeys:[NSArray arrayWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil]]; NSScanner* scan = [NSScanner scannerWithString:[cardNo substringToIndex:17]]; int val; BOOL isNum = [scan scanInt:&val] && [scan isAtEnd]; if (!isNum) { return NO; } int sumValue = 0; for (int i =0; i<17; i++) { sumValue+=[[cardNo substringWithRange:NSMakeRange(i , 1) ] intValue]* [[codeArray objectAtIndex:i] intValue]; } NSString* strlast = [checkCodeDic objectForKey:[NSString stringWithFormat:@"%d",sumValue%11]]; if ([strlast isEqualToString: [[cardNo substringWithRange:NSMakeRange(17, 1)]uppercaseString]]) { return YES; } return NO; }

41,響應者鏈條順序

1> 當應用程序啓動之後建立 UIApplication 對象 2> 而後啓動「消息循環」監聽全部的事件 3> 當用戶觸摸屏幕的時候, "消息循環"監聽到這個觸摸事件 4> "消息循環" 首先把監聽到的觸摸事件傳遞了 UIApplication 對象 5> UIApplication 對象再傳遞給 UIWindow 對象 6> UIWindow 對象再傳遞給 UIWindow 的根控制器(rootViewController) 7> 控制器再傳遞給控制器所管理的 view 8> 控制器所管理的 View 在其內部搜索看本次觸摸的點在哪一個控件的範圍內(調用Hit test檢測是否在這個範圍內) 9> 找到某個控件之後(調用這個控件的 touchesXxx 方法), 再一次向上返回, 最終返回給"消息循環" 10> "消息循環"知道哪一個按鈕被點擊後, 在搜索這個按鈕是否註冊了對應的事件, 若是註冊了, 那麼就調用這個"事件處理"程序。(通常就是執行控制器中的"事件處理"方法)

42,使用函數式指針執行方法和忽略performSelector方法的時候警告

不帶參數的:
SEL selector = NSSelectorFromString(@"someMethod"); IMP imp = [_controller methodForSelector:selector]; void (*func)(id, SEL) = (void *)imp; func(_controller, selector); 帶參數的: SEL selector = NSSelectorFromString(@"processRegion:ofView:"); IMP imp = [_controller methodForSelector:selector]; CGRect (*func)(id, SEL, CGRect, UIView *) = (void *)imp; CGRect result = func(_controller, selector, someRect, someView); 忽略警告: #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" [someController performSelector: NSSelectorFromString(@"someMethod")] #pragma clang diagnostic pop 若是須要忽視的警告有多處,能夠定義一個宏: #define SuppressPerformSelectorLeakWarning(Stuff) \ do {\ _Pragma("clang diagnostic push") \ _Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"") \ Stuff; \ _Pragma("clang diagnostic pop") \ } while (0) 使用方法: SuppressPerformSelectorLeakWarning( [_target performSelector:_action withObject:self] );

43,UIApplication的簡單使用

--------設置角標數字--------
    //獲取UIApplication對象 UIApplication *ap = [UIApplication sharedApplication]; //在設置以前, 要註冊一個通知,從ios8以後,都要先註冊一個通知對象.纔可以接收到提醒. UIUserNotificationSettings *notice = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil]; //註冊通知對象 [ap registerUserNotificationSettings:notice]; //設置提醒數字 ap.applicationIconBadgeNumber = 20; --------設置聯網狀態-------- UIApplication *ap = [UIApplication sharedApplication]; ap.networkActivityIndicatorVisible = YES; --------------------------



文/品味_生活(簡書做者) 原文連接:http://www.jianshu.com/p/7c3ee5e67d03 著做權歸做者全部,轉載請聯繫做者得到受權,並標註「簡書做者」。
相關文章
相關標籤/搜索