iOS Development-Development Summary (VI)

Source: Internet
Author: User

Use of pointers in Swift

In Swift, pointers are represented by a special type, which is unsafepointer<t>. Following Cocoa's consistent immutable principle,,unsafepointer<t> is also immutable. Of course, it also has a variable variant,,unsafemutablepointer<t>. Most of the time, pointers in C are introduced to Swift in both types: The const-decorated pointer in C corresponds to Unsafepointer (the most common is the const char * of the C string), while the other mutable pointers correspond to Unsafemuta Blepointer. In addition, there is a unsafebufferpointer<t&gt in Swift that represents a set of continuous data pointers, an opaque pointer copaquepointer that represents an incomplete structure, and so on. In addition you may have noticed that the type of pointer to the content can be determined to be a generic struct, and we can use this generic to constrain the type that the pointer points to to provide some security.

For a unsafepointer<t> type, we can use the memory property to value it, if the pointer is a variable unsafemutablepointer<t> type, we can also pass the memory Assign a value to it. For example, if we want to write a counter that uses pointers to manipulate memory directly, you can do this:
Func Incrementor (ptr:unsafemutablepointer<int>) {    Ptr.memory + = 1}var A = 10incrementor (&a)

A//11 Oc-js Simple Package
[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 See the properties of the class in IB's Attribute Inspector (property inspector), and ibdesignable can update the view in real time.
@IBDesignable class Customview:uiview {    @IBInspectable var bordercolor:uicolor = Uicolor.clearcolor ()      @ ibinspectable var borderwidth:cgfloat = 0      @IBInspectable var cornerradius:cgfloat = 0  }


Quick Find Controller
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)     }11     func Findcontrollerwithclass<t> (Clzz:anyclass), T? {         responder = Self.nextresponder () (         responder! = nil) {             if (responder!. Iskindofclass (clzz)) {                 return responder as? T17             }18             responder = responder? Nextresponder ()         }20         return nil22     }23}25  if ui_user_interface_idiom () = =. Pad {     //device is iPad29}30 if uiinterfaceorientationisportrait (orientation) {+     //Screen is vertical 33}

Xcode by default with HTTPS solutions

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

Ibinspectable View the properties of the class in IB's Attribute Inspector (property inspector), while ibdesignable can update the view in real time

Ibdesignable
Main function: You can display the interface that you write with the code.
How to use: In swift, @IBDesignable keyword is written before class.
In OC, is ib_designable this keyword, written before @implementation can
Ibinspectable
Main role: Visualize the variables in the view, and can be modified to see immediately

How to use: In swift, @IBInspectable keyword is written before the variable that needs to be displayed
In OC, this is the Ibinspectable keyword, which is written before the variable that needs to be displayed.
Additional two shortcut keys are included:
Command+shift+o, quickly open the required files
control+shift+ Mouse Left click SB, you can choose the need of SB alive view

 1//1. Get all files in the Images folder 2 nsstring *sourcepath = @ "/USERS/APPLE/DESKTOP/ABC"; 3 NSString *dest = @ "/users/apple/desktop/lnj"; 4 5//2. Get all the files in the Images folder 6 Nsfilemanager *mgr = [Nsfilemanager Defaultmanager]; 7 Nsarray *subpaths = [Mgr Subpathsatpath:sourcepath]; 8//NSLog (@ "%@", subpaths); 9//3. Cut the file into the Lnj folder for (int i = 0; i < Subpaths.count; i++) {12//3.1 Gets the name of the file currently traversed Nsstrin G *filenmae = subpaths[i];14//3.2 According to the name of the current file, stitching the full path to the nsstring *frompath = [SourcePath stringbyappendingpathcomp onent:filenmae];16 nsstring *topath = [dest stringbyappendingpathcomponent:filenmae];17 NSLog (@ "FromPath =%@",      Frompath) NSLog (@ "Topath =%@", topath); [Mgr Moveitematpath:frompath Topath:topath error:nil];21 }22 dispatch_apply (Subpaths.count, dispatch_get_global_queue (0, 0), ^ (size_t index) {24//3.1 Get current times      The name of the document to be nsstring *filenmae = subpaths[index];26   3.2 According to the name of the current file, stitching the full path of nsstring *frompath = [SourcePath stringbyappendingpathcomponent:filenmae];28 N sstring *topath = [dest stringbyappendingpathcomponent:filenmae];29 NSLog (@ "Frompath =%@", frompath);     SLog (@ "Topath =%@", topath); [Mgr Moveitematpath:frompath Topath:topath error:nil];33 34   }); 35

Checking the availability of methods

Use Respondstoselector to check if this method is included in the frame. For example: IOS 9 has a new allowsbackgroundlocationupdates attribute in the core location framework:

Cllocationmanager *manager = [Cllocationmanager new];if ([Manager respondstoselector: @selector ( Setallowsbackgroundlocationupdates:)] {  //Not available in iOS 8  manager.allowsbackgroundlocationupdates = YES;}
Trap

These methods are difficult to maintain, and they are not as secure as they seem. Perhaps an API is now public, but it may be private in earlier versions. For example: IOS 9 has several new text styles, such as uifonttextstylecallout. If you only want to use this style in iOS 9, you can check that it exists because it should be null in iOS 8:
if (uifonttextstylecallout) {  Textlabel.font = [Uifont preferredfontfortextstyle:uifonttextstylecallout];}

Unfortunately, the result is not so. It turns out that this flag exists in iOS 8, but it's not declared public. Using a private method or value can have unpredictable results, and this is different from what we think.

Method of Swift 2

The Swift 2 has built-in usability checks, and is checked at compile time. This means that when we use an API that is not available for the current deployment version, Xcode can notify us. For example, if I use Cncontactstore,xcode in a deployment version of iOS 8, the following improvements will be made:
If #available (IOS 9.0, *) {let  store = Cncontactstore ()} else {  //old version of Case}

It can also replace the respondstoselector we used earlier:
Let manager = Cllocationmanager () if #available (IOS 9.0, *) {  manager.allowsbackgroundlocationupdates = true}

Usage Scenarios for usability checks


#available条件适用于一系列平台 (IOS, OSX, WatchOS) and version numbers. For example, for code that runs only on iOS 9 or OS X 10.10:

If #available (iOS 9, OSX 10.10, *) {  //code to be executed on iOS 9 or OS X 10.10}
Even if your app is not deployed on other platforms, you will need to include them with the * wildcard characters at the end.

If a block of code is executed only on a specific platform version, you can return it in advance with the guard declaration with #available, which will enhance readability:
Private Func somethingnew () {  guard #available (iOS 9, *) else {return}  //code executed in iOS 9 let  store = cncontact Store () let  predicate = Cncontact.predicateforcontactsmatchingname ("Zakroff") let  keys = [ Cncontactgivennamekey, Cncontactfamilynamekey]  ...}

If the entire method or class exists only under a specific platform version, use @available:
@available (IOS 9.0, *) private func checkcontact () {let  store = Cncontactstore ()  //...}

Compile-time Security checks


Before we finish, let's look at the constant in iOS 9 that is public but private in iOS 8. If the deployment version is iOS 8, we set the font to a style that only iOS 9 can use, which results in a compilation error:

Label.font = Uifont.preferredfontfortextstyle (uifonttextstylecallout)
    • > ' Uifonttextstylecallout ' is only available on IOS 9.0 or newer
Swift makes it easy to debug and can assign a reasonable value to the platform version:
If #available (IOS 9.0, *) {  Label.font = Uifont.preferredfontfortextstyle (uifonttextstylecallout)} else {  Label.font = Uifont.preferredfontfortextstyle (uifonttextstylebody)}

iOS Development-Development Summary (VI)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.