iOS開發-開發總結(六)

來源:互聯網
上載者:User

標籤:

swift中指標的使用

在 Swift 中,指標都使用一個特殊的類型來表示,那就是 UnsafePointer<T>。遵循了 Cocoa 的一貫不可變原則,UnsafePointer<T> 也是不可變的。當然對應地,它還有一個可變變體,UnsafeMutablePointer<T>。絕大部分時間裡,C 中的指標都會被以這兩種類型引入到 Swift 中:C 中 const 修飾的指標對應 UnsafePointer (最常見的應該就是 C 字串的 const char * 了),而其他可變的指標則對應 UnsafeMutablePointer。除此之外,Swift 中存在表示一組連續資料指標的 UnsafeBufferPointer<T>,表示非完整結構的不透明指標 COpaquePointer 等等。另外你可能已經注意到了,能夠確定指向內容的指標類型都是泛型的 struct,我們可以通過這個泛型來對指標指向的類型進行約束以提供一定安全性。

對 於一個 UnsafePointer<T> 類型,我們可以通過 memory 屬性對其進行取值,如果這個指標是可變的 UnsafeMutablePointer<T> 類型,我們還可以通過 memory 對它進行賦值。比如我們想要寫一個利用指標直接操作記憶體的計數器的話,可以這麼做:
func incrementor(ptr: UnsafeMutablePointer<Int>) {    ptr.memory += 1}var a = 10incrementor(&a)

a  // 11OC-JS簡單封裝
[webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement(‘script‘);"           "script.type = ‘text/javascript‘;"           "script.text = \"function myFunction() { "           "var field = document.getElementsByName(‘q‘)[0];"           "field.value=‘iCocos‘;"           "document.forms[0].submit();"           "}\";"           "document.getElementsByTagName(‘head‘)[0].appendChild(script);"];                   [webView stringByEvaluatingJavaScriptFromString:@"myFunction();"];
 IBInspectable在IB的Attribute Inspector(屬性偵測器)中查看類的屬性,而IBDesignable能即時更新視圖,很厲害吧!
@IBDesignable class CustomView : UIView {    @IBInspectable var borderColor: UIColor = UIColor.clearColor()      @IBInspectable var borderWidth: CGFloat = 0      @IBInspectable var cornerRadius: CGFloat = 0  }


 快速尋找控制器
 1 extension UIView { 2  3  4     func findController() -> UIViewController! { 5         return self.findControllerWithClass(UIViewController.self) 6     } 7  8     func findNavigator() -> UINavigationController! { 9         return self.findControllerWithClass(UINavigationController.self)10     }11 12     func findControllerWithClass<T>(clzz: AnyClass) -> T? {13         var responder = self.nextResponder()14         while(responder != nil) {15             if (responder!.isKindOfClass(clzz)) {16                 return responder as? T17             }18             responder = responder?.nextResponder()19         }20 21         return nil22     }23 24 }25  26  27 if UI_USER_INTERFACE_IDIOM() == .Pad {  28     // 裝置是 iPad29 }30 31 if UIInterfaceOrientationIsPortrait(orientation) {  32     // 螢幕是豎屏33 }

 

Xcode預設使用https的解決方案

<key>NSAppTransportSecurity</key><dict>    <key>NSAllowsArbitraryLoads</key>    <true/></dict>

 

IBInspectable在IB的Attribute Inspector(屬性偵測器)中查看類的屬性,而IBDesignable能即時更新視圖

IBDesignable 
主要作用:可以顯示出來你使用代碼寫的介面。
使用方法:在swift裡,@IBDesignable關鍵字寫在class前即可。 
在OC裡,是IB_DESIGNABLE這個關鍵字,寫在@implementation前即可 
IBInspectable 
主要作用:使view內的變數可視化,並且可以修改後馬上看到 

使用方法:在swift裡,@IBInspectable關鍵字寫在需要顯示的變數前即可 
在OC裡,是IBInspectable這個關鍵字,寫在需要顯示的變數前即可 
另外附兩個快速鍵: 
command+shift+O,快速開啟需要的檔案 
control+shift+滑鼠左擊sb,可以選擇需要的sb活著view

   
 1 // 1.擷取images檔案夾中所有的檔案 2     NSString *sourcePath = @"/Users/apple/Desktop/abc"; 3     NSString *dest = @"/Users/apple/Desktop/lnj"; 4      5     // 2.擷取images檔案夾中所有的檔案 6     NSFileManager *mgr = [NSFileManager defaultManager]; 7     NSArray *subPaths = [mgr subpathsAtPath:sourcePath]; 8     //    NSLog(@"%@", subPaths); 9     // 3.剪下檔案到lnj檔案夾中10  11      for (int i = 0; i < subPaths.count; i++) {12      // 3.1擷取當前遍曆到得檔案的名稱13      NSString *fileNmae = subPaths[i];14      // 3.2根據當前檔案的名稱, 拼接全路徑15      NSString *fromPath = [sourcePath stringByAppendingPathComponent:fileNmae];16      NSString *toPath = [dest stringByAppendingPathComponent:fileNmae];17      NSLog(@"fromPath = %@", fromPath);18      NSLog(@"toPath = %@", toPath);19      20      [mgr moveItemAtPath:fromPath toPath:toPath error:nil];21      }22     23     dispatch_apply(subPaths.count, dispatch_get_global_queue(0, 0), ^(size_t index) {24         // 3.1擷取當前遍曆到得檔案的名稱25         NSString *fileNmae = subPaths[index];26         // 3.2根據當前檔案的名稱, 拼接全路徑27         NSString *fromPath = [sourcePath stringByAppendingPathComponent:fileNmae];28         NSString *toPath = [dest stringByAppendingPathComponent:fileNmae];29         NSLog(@"fromPath = %@", fromPath);30         NSLog(@"toPath = %@", toPath);31         32         [mgr moveItemAtPath:fromPath toPath:toPath error:nil];33         34     });35  

 

 檢查方法的可用性

用respondsToSelector檢查架構內是否含有此方法。例如:iOS 9在Core Location架構中新增了allowsBackgroundLocationUpdates屬性:

CLLocationManager *manager = [CLLocationManager new];if ([manager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)]) {  // 在iOS 8中不可用  manager.allowsBackgroundLocationUpdates = YES;}
陷阱

這 些方法既難以維護,又沒有看上去那麼安全。也許某個API現在是公有的,但在早期的版本中卻有可能是私人的。例如:iOS 9中新增了幾個文本樣式,如UIFontTextStyleCallout。如果只想在iOS 9中使用這種樣式,你可以檢查其是否存在,因為它在iOS 8中應該是null的:
if (UIFontTextStyleCallout) {  textLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleCallout];}

 

不幸的是結果並非如此。原來這個標誌在iOS 8中是存在的,只是沒有宣布公有。使用一個私人的方法或值有可能出現難以預料的結果,況且這也和我們的想法不同。

Swift 2的方法

Swift 2內建了可用性檢查,而且是在編譯時間進行檢查。這意味著當我們使用當前部署版本停用API時,Xcode能夠通知我們。例如:如果我在部署版本為iOS 8的情況下使用CNContactStore,Xcode將提出以下改進:
if #available(iOS 9.0, *) {  let store = CNContactStore()} else {  // 舊版本的情況}

同樣這可以取代我們之前使用的respondsToSelector:
let manager = CLLocationManager()if #available(iOS 9.0, *) {  manager.allowsBackgroundLocationUpdates = true}

可用性檢查的使用情形


#available條件適用於一系列平台(iOS, OSX, watchOS) 和版本號碼。例如:對於只在iOS 9或OS X 10.10上啟動並執行代碼:
 
if #available(iOS 9, OSX 10.10, *) {  // 將在iOS 9或OS X 10.10上執行的代碼}
即使你的App並沒有部署在其他平台,最後也需要用*萬用字元來包括它們。

如果某塊代碼只在特定的平台版本下執行,你可以用guard聲明配合#available來提前return,這樣可以增強可讀性:
private func somethingNew() {  guard #available(iOS 9, *) else { return }  // 在iOS 9中執行的代碼  let store = CNContactStore()  let predicate = CNContact.predicateForContactsMatchingName("Zakroff")  let keys = [CNContactGivenNameKey, CNContactFamilyNameKey]  ...}

如果整個方法或類只在特定的平台版本下存在,用@available:
@available(iOS 9.0, *)private func checkContact() {  let store = CNContactStore()  // ...}

編譯時間的安全性檢查


結束前,讓我們再看看那個常量在iOS 9中公有卻在iOS 8中私人的問題。如果部署版本為iOS 8,我們卻把字型設定為一個只有iOS 9才能用的樣式,這將產生一個編譯錯誤:
 
label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCallout)
  • > ‘UIFontTextStyleCallout‘ is only available on iOS 9.0 or newer
Swift使其便於調試,同時能夠根據平台版本賦一個合理的值:
if #available(iOS 9.0, *) {  label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCallout)} else {  label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)}

iOS開發-開發總結(六)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.