[BS] 小知識點總結-02

1.  dispatch_GCD 可以讓某操做延遲x秒執行php

    //模擬網速慢,延遲3s返回數據(就會致使右側數據和左側標籤不對應)ios

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{程序員

        [[AFHTTPSessionManager manager] GET:@"http://api.budejie.com/api/api_open.php" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) { //AFN在子線程中發送HTTP請求,一旦獲取responseObject值,就會來到success後面的block,該block屬於mainThread主線程,以便刷新UI界面。api

            NSArray *users = [WZRecommendUser mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];//字典數組轉模型數組數組

        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {緩存

        }];網絡

    }); session

2. 內存警告的監聽:多線程

2.1 AppDelgate.m中有這樣的代理方法,能夠監聽整個app的內存警告架構

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

      // try to clean up as much memory as possible. next step is to terminate app

}

 2.2 ViewController.m中的didReceiveMemoryWarning也能夠

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

}

3. 數組添加對象的2種方法

[aArray addObjects: bArray]; //把b數組總體存入aArray[0]位置

[aArray addObjectsFromAArray: bArray];//把b數組中每一個元素存到a數組對應的位置

4. OC中id類型的對象(如直接從數組取出的對象、或經過key從字典中取出的對象)不能使用點語法,可是能夠採用方括號方法調用。

5. 在數據模型中聲明的NSMutableArray屬性,必須懶加載重寫get方法才能在另外一個類中動態的添加對象。由於NSMutable**類型的變量,必須先初始化,而後才能使用。

6.

MJRefresh中的mj_header必須顯性調用[self.tableView.mj_header beginRefreshing]; 纔會顯示並執行block,或者用戶手指下拉時才顯示並執行block。但header一旦顯示,就必須顯性調用[self.tableView.mj_header endRefreshing];纔會隱藏。

MJRefresh中的mj_footer默認是顯示的,須要在tableView的數據源方法numberOfRowsInSection中設置是否隱藏【self.tableView.mj_footer.hidden = (model.count == 0); 】。只要tableView頁面滾動到footer的位置,就會自動觸發footer加載動畫,並執行block中代碼。footer加載動畫啓動後,也須要顯性調用endRefreshing或者endRefreshingWithNoMoreData來中止加載動畫。

7.

- (void)dealloc { //全部的AFN請求都使用self.sessionManager發送

    //控制器銷燬或退出時,讓sessionManager隊列中全部的操做取消

    [self.sessionManager.operationQueue cancelAllOperations];

}

8. 在用戶屢次快速點擊,連續發送請求時,如何只處理最後一次請求

    //1.參數
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"list";
    params[@"c"] = @"subscribe";
    //全局的屬性變量只保存最後一次網絡請求數據
    self.paragsDict = params;
    
    //2.請求
    [self.sessionManager GET:@"http://api.budejie.com/api/api_open.php" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
    {
        //self.paragsDict中保存的是最後一次點擊的請求參數,而parags是局部變量,parags存的是當時發請求的參數,若是不相等,說明這不是最後一次請求,不處理。只處理最後一次請求。
        if (self.paragsDict != params)  return;
             
        //字典數組轉模型數組
        //刷新右側表格數據,調cellForRow方法
        [self.userTableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //若是不相等,說明這不是最後一次請求,不處理。只處理最後一次請求。
        if (self.paragsDict != params)  return;
        [SVProgressHUD showErrorWithStatus:@"網絡繁忙,右側數據獲取失敗"];//會自動關閉
    }];

 9. NSData和NSArray相互轉換:

    NSArray *arr1 = [[NSArray alloc]initWithObjects:@"0",@"5",nil];
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:arr1];
    NSArray *arr2 = [NSKeyedUnarchiver unarchiveObjectWithData:data];

10. 固定自定義控件的長寬

  若是想讓一個自定義的UI控件的尺寸(長寬)不能被改變,只需在該類.m中重寫setFrame和setBounds方法,將frame和bounds修改成固定大小,而後調用super方法將設定好的frame和bounds傳進去便可。

11. 自定義鍵盤

  // 更換鍵盤(如表情鍵盤)

    UIView *keyboard = [[UIView alloc] init];

    keyboard.frame = CGRectMake(0, 0, 0, 100);

    keyboard.backgroundColor = [UIColor redColor];

    self.emailField.inputView = keyboard;

    // 設置鍵盤頂部的工具條;

    UIView *toolbar = [[UIView alloc] init];

    toolbar.frame = CGRectMake(0, 0, 0, 44);

    toolbar.backgroundColor = [UIColor blueColor];

    self.nameField.inputAccessoryView = toolbar;

12. UITableViewWrapperView

  在iOS7如下系統,UITableViewCell.superview就是 UITableView,但在IOS7中,cell上面還多了一個 UITableViewWrapperView,因此須要 UITableViewCell.superview.superview獲取UITableView 

13. 讓TabelViewCell左右留出空白間距,下方留出空白間距做爲分割線

  12.1 設置cell的contentView的frame

  12.2 直接在conte

14.打印當前app的info.plist文件

  NSLog(@"%@",[UIBundle mainBundle].infoDictionary);

15. UIView有個屬性@property(nonatomic, strong) UIColor *tintColor 用來設置鼠標顏色、漸變色、導航顏色等。例如設置UITextField聚焦時光標的顏色,就能夠用:textField.tintColor = [UIColor redColor];光標被修改成紅色。

16. ios程序的編譯、連接、打包、安裝、執行

程序開發好了Xcode會調用Mac系統的clang編譯器會將程序員寫的每一個類.h/.m(源文件)進行編譯,產生目標文件.o,而後將全部的目標文件+引用的框架文件,連接在一塊兒,產生一個可執行的二進制文件.Mach-O,可執行程序文件.Mach-O包括BSS段、數據段代碼段(也稱文本段)。它們都是有編譯器在程序運行前就分配好的。應用程序安裝包,是使用Xcode的Organizer-Archives將可執行文件.Mach-O+資源文件(圖片/聲音/plist)、nib、第三方bundle所有打包成一個.app的壓縮包,而後再打包成.ipa格式,發放給用戶安裝在手機上。(本身理解,可能有誤)

補充:

Xcode 的默認編譯器是 clang。本文中咱們提到的編譯器都表示 clang。clang 的功能是首先對 Objective-C 代碼作分析檢查,而後將其轉換爲低級的類彙編代碼:LLVM Intermediate Representation(LLVM 中間表達碼)。接着 LLVM 會執行相關指令將 LLVM IR 編譯成目標平臺上的本地字節碼,這個過程的完成方式能夠是即時編譯 (Just-in-time),或在編譯的時候完成。

LLVM 指令的一個好處就是能夠在支持 LLVM 的任意平臺上生成和運行 LLVM 指令。例如,你寫的一個 iOS app, 它能夠自動的運行在兩個徹底不一樣的架構(Inter 和 ARM)上,LLVM 會根據不一樣的平臺將 IR 碼轉換爲對應的本地字節碼。

 17. 全部的UIView都有一個- (void)layoutIfNeeded方法,可以讓View當即刷新狀態(佈局子視圖)。使用UIAppearance設置導航按鈕狀態後,再修改導航按鈕disable狀態就不會奏效,此時需讓[navigationBar layoutIfNeeded];

Description: Lays out the subviews immediately. Use this method to force the layout of subviews before drawing. Using the view that receives the message as the root view, this method lays out the view subtree starting at the root.

18.

在iOS開發中,常常要考慮系統的向下兼容,若是使用了低版本不存在的API ,則不能向下兼容,這時候若是想兼容低版本,就須要根據當前設備的版本進行不一樣的處理,在低版本中可能要犧牲一些新功能。判斷iOS版本以便向下兼容代碼一般寫法:

if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
// iOS 8.0以上 code

}
else {
// iOS 8.0如下 code
}

//能夠定義一個宏來判斷,以方便使用 

#define  IOS_VERSION_5_OR_ABOVE   (([[[UIDevice currentDevice] systemVersion] floatValue] >= 5.0)? (YES):(NO))

 

 

//如下2個宏和使用的Xcode及Xcode的設定值有關。不能用來斷定軟件版本號。

NSLog(@"MAX:%d",__IPHONE_OS_VERSION_MAX_ALLOWED);//MAX是Xcode中Develop Target可以設置的最大值,例如Xcode7.0最多能開發iOS9.0的軟件

NSLog(@"MIN:%d",__IPHONE_OS_VERSION_MIN_REQUIRED);//MIN宏就是Xcode中Develop Target當前設定的值

2016-06-05 15:16:58.315 PlayMusicAndSound[3041:216356] MAX:90000

2016-06-05 15:16:58.315 PlayMusicAndSound[3041:216356] MIN:80000

 

 

//下面是ios內其餘相關信息的判斷方法
獲取進程信息和設備信息(包括設備類型,序列號,ios版本等)
[[NSProcessInfo processInfo] globallyUniqueString],
[[NSProcessInfo processInfo] hostName],
[[NSProcessInfo processInfo] operatingSystemName],
[[NSProcessInfo processInfo] operatingSystemVersionString],
[[NSProcessInfo processInfo] physicalMemory],
[[NSProcessInfo processInfo] processName]);
——————————————————————————————
[UIDevice currentDevice].uniqueIdentifier,
[UIDevice currentDevice].name,
[UIDevice currentDevice].systemName,
[UIDevice currentDevice].systemVersion,
[UIDevice currentDevice].model,
[UIDevice currentDevice].localizedModel,
[UIDevice currentDevice].batteryLevel

19.   AVAudioPlayer  AVPlayer的區別

   * AVAudioPlayer,該類帶Audio,說明只能播放本地音樂。並且一個audioPlayer只能包含一個url,只能播放一個音頻文件。

   * AVPlayer, 便是Audio Vedio Player, 既能播放本地的音頻、視頻,又能播放網上的音頻、視頻

注意:正式開發過程當中iOS項目名稱必定不要有漢字或奇怪的符號,可能致使播放本地視頻/音頻時,URL出現莫名其妙的錯誤

20. 由於block會默認對其中使用的對象進行強引用,Block裏使用Block外面定義的局部變量,也需在局部變量前加上__block來保證局部變量在出了方法的{}做用域後不被銷燬,等到block中代碼執行完了才銷燬。

通常在控制器中使用多線程下載圖片/文件等,如dispatch_async/sync函數,NSBlockOperation操做都會使用block,在這些Block中若是使用self控制器的屬性,就可能構成循環引用。

例如:self.queue = [[NSOperationQueue alloc]init];    [self.queue addOperation:operation];  

operation = [NSBlockOperation blockOperationWithBlock:^{  NSData *data = [NSData dataWithContentsOfURL: modal.url];

self.imagesDict[model.url] = [UIImage imageWithData: data];  }];

以上代碼: 控制器強引用operationQueue, operationQueue又強引用operation,operation中的block又使用控制器的imagesDict字典,block默認對使用的控制器self進行強引用,這樣就會致使控制器self和operation互相強引用,造成循環引用。

解決以上問題的方法是:在operation的Block外面定義一個控制器的若引用,在Block中使用該弱引用來調用控制器的imagesDict字典。

__weak typeof(self)  vc = self;  //注意typeof(self)是獲取類型的函數,至關於__weak UIViewController *  vc = self;

operation = [NSBlockOperation blockOperationWithBlock:^{  NSData *data = [NSData dataWithContentsOfURL: modal.url];

vc.imagesDict[model.url] = [UIImage imageWithData: data];  }];

注意:若是隻是block引用控制器,控制器沒有對block進行強引用,則不須要使用弱引用的控制器。

[UIView animateWithDuration: 1.0 animations:^{

        self.view.bounds = CGRectMake(0, 0, 200, 200);

    }]; //僅僅是block對控制器引用

21.

若是下載操做很是複雜,代碼很是多,能夠考慮將下載操做放在自定義operation,能夠新建一個繼承自NSOperation的子類WZOperation,之後使用WZOperation *opt = [[WZOperation alloc]init]; 建立操做,而且將它添加到隊列[[NSOperationQueue alloc]init] addOperation: opt]; 這行代碼就會當即調用WZOperation.m中重寫的-(void)main{}方法中的代碼。

WZOperation.m代碼的固定寫法

- (void)main {

  @autoreleasepool{ //在異步線程建立的autorelease對象沒法添加到主線程的main()函數中的自動釋放池。

    if (self.isCancel) return; //每作完一段耗時操做先後都要判斷是否被取消。

      //寫自定義的代碼

    if (self.isCancel) return;

  }

}

 

***注意:NSOperationQueue中有100個操做operaion, 若是下載到28個,還有2個線程正在下載,還沒有完成,此時若是調用[queue cancelAllOperation]; 只會取消後面70個還沒有開始下載的操做,對已經完成的和正在下載的操做沒有任何影響。

22.

SDWebImage經過imageIO框架來播放gif(幀動畫)。能夠設置按期清理緩存。

//應用程序代理可監控ios系統發來的內存警告,而後在分發給每一個實現- (void)didReceiveMemoryWarning{}方法的控制器
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    
    //SDWebImage中兩個重要的單例:SDWebImageManager 和 SDImageCache
    
    [[SDWebImageManager sharedManager] cancelAll]; //取消全部操做(正在下載的不會取消)
    [[SDWebImageManager sharedManager].imageCache clearMemory]; //經過Manager拿到imageCache單例,清除內存
    
    [[SDImageCache sharedImageCache] clearMemory];//清除內存緩存
    [[SDImageCache sharedImageCache] clearDisk]; //清除硬盤緩存
    [[SDImageCache sharedImageCache] cleanDisk];//清理過時的緩存 (默認爲7天)
    NSUInteger cacheBytes = [SDImageCache sharedImageCache].getSize; //獲取硬盤上已緩存的字節B數
    
    //可經過SDImageCache的以下屬性設置緩存天數
    /**
     * use memory cache [defaults to YES]
     */
    @property (assign, nonatomic) BOOL shouldCacheImagesInMemory;
    
    /**
     * The maximum "total cost" of the in-memory image cache. The cost function is the number of pixels held in memory.
     */
    @property (assign, nonatomic) NSUInteger maxMemoryCost;
    
    /**
     * The maximum number of objects the cache should hold.
     */
    @property (assign, nonatomic) NSUInteger maxMemoryCountLimit;
    
    /**
     * The maximum length of time to keep an image in the cache, in seconds
     */
    @property (assign, nonatomic) NSInteger maxCacheAge;
    
    /**
     * The maximum size of the cache, in bytes.
     */
    @property (assign, nonatomic) NSUInteger maxCacheSize;
}

23.

相關文章
相關標籤/搜索