This is followed by the following in the previous post:
--core Foundation
Frame
The Core Foundation framework is Apple's offering a set of concepts derived from the foundation framework, programming interfaces for C-style APIs. While it is cumbersome to invoke this C-style API in Swift, it is sometimes convenient to use the Core Foundation framework's APIs during OS X and iOS development, for example, when coding with the C language.
The Core Foundation framework is closely related to the foundation framework, and they have the same interface, but different. The Core Foundation framework is based on the C language style, and the foundation framework is based on the Objective-c language style. In OS X and iOS program code, there is often a mixture of multiple language-style code, which makes our development more cumbersome.
Data type Mappings
The core Foundation framework provides some opaque data types that encapsulate data and operations, they can also be called "classes," they all inherit from the Cftype class, and Cftype is the root class of the core foundation framework type used. These data types have corresponding data types in the foundation framework, and some of these data types have a corresponding relationship to the swift native data type.
See examples of conversions between the swift native type and the core foundation type:
Import corefoundation
import Foundation
var cfstring "Hello,world" //Create cfstring string
var String As String //Convert cfstring string to Swift native string stringvar cfstring = str // Converts a swift native string to a cfstring string
The conversion of a core foundation type to a swift native type is required to force type conversions during this transition.
--core Foundation
framework of memory management
Objective-c's MRC Memory Management
Core Foundation's memory management is inseparable from the MRC memory management of OBJECTIVE-C, and first introduces Objective-c's MRC memory management.
All objective-c classes inherit the NSObject class, and each NSObject object has an internal counter that tracks the number of references to the object, called the reference count (Reference count, or RC). When the object is created, the reference count is 1. In order to guarantee the existence of an object, the Retain method can be called to persist the object, the Retain method makes its reference count plus 1, and if this object is not required to call the release or Autorelease method, the release or Autorelease method makes its reference count minus 1. The system runtime frees object memory when the object's reference count is 0. The
Reference count example first creates a NSObject object in ① A, when the object reference count is 1. To use this NSObject object in ② B, use the NSObject object reference, but to prevent the NSObject object from being freed during use, you can call the Retain method to add 1 to the reference count, and the reference count is 2. Call the release or Autorelease method in step ③ A to reduce the reference count by 1, at which point the reference count is 1. Call the release or Autorelease method in ④ C, just get the NSObject object reference, and do not call the retain, release, or Autorelease methods, so there is no change in the reference count. Call the release or Autorelease method in ⑤ B to reduce the reference count by 1, at which point the reference count is 0. At this point, the NSObject object will be freed by memory.
To summarize:
- Who creates or copies an object, he must also be responsible for invoking the NSObject object release or Autorelease method, so that the reference count minus 1, in the caller a in step ①, responsible for creating the NSObject object, then caller a must be responsible for the reference count minus 1, see step ④.
- Who calls the Retain method to make the reference count plus 1, it must also be responsible for invoking the NSObject object release or Autorelease method, so that the reference count minus 1, in the caller B in step ②, caller B calls the NSObject object retain method to make the reference count plus 1, Then caller B must also be responsible for reducing the reference count by 1, see step ⑤.
Object ownership
An object can have one or more owners, from the owner's point of view it has "ownership" of the object, from which the caller A and the caller B are the owners, they may be a program, may be an object. They have ownership of the NSObject object and are no longer in use when they should be responsible for discarding object ownership, and when the object has no owner, the reference count is 0 and it can be freed.
If you interpret object ownership: Caller a creates or copies a NSObject object, then caller A has ownership of the NSObject object, see step ①. Caller B calls the NSObject object retain method and obtains ownership of the NSObject object as well, see step ②. Caller a calls the NSObject object release method to discard ownership of the NSObject object, see step ③. Caller C simply uses the NSObject object without obtaining ownership of the NSObject object, see step ④. Caller B calls the NSObject object release method, discards the ownership of the NSObject object, see step ⑤, but when caller B uses the NSObject object, the NSObject object is freed because the other caller discards the ownership. Then the program in Caller B has a run-time error.
--core Foundation
framework of memory managed objects vs . Unmanaged objects
When you call the core foundation function in Swift to get an object, the object is divided into: Memory managed objects and memory unmanaged objects.
• Memory Managed Objects
A memory managed object is a compiler that helps manage memory, and we don't need to call the Cfretain function to take ownership of the object, or call the Cfrelease function to discard the object ownership.
The way to get these memory managed objects is to use the cf_returns_retained or cf_returns_not_retained annotation declaration
_ Cstr:unsafepointer<int8>,
_ encoding:cfstringencoding) cfstring //Memory managed Objects
Func Cfhostcreatecopy (_ Alloc:cfallocator?,
_ Host:cfhost) unmanaged < cfhost //Memory Unmanaged Object
• Memory unmanaged objects
Memory unmanaged objects are memory that needs to be managed by the programmer himself. This is because the compiler cannot help manage memory because the cf_returns_retained or cf_returns_not_retained comment Declaration is not used in the method that obtains the object. We can use the previous section to determine whether a non-memory managed object is used in a specific way.
Memory unmanaged objects are cumbersome to use, and are handled appropriately according to the method of acquiring ownership.
- If a function name contains create or copy, the caller obtains the object's ownership at the same time, and the return value unmanaged<t> needs to call the Takeretainedvalue () method to get the object. When the caller no longer uses the object, the SWIFT code needs to call the Cfrelease function to discard the object ownership, because Swift is managed by arc memory.
- If a function name contains a GET, the caller obtains the object without taking ownership of the object, and the return value unmanaged<t> needs to call the Takeunretainedvalue () method to get the object.
--cocoa Touch
A single case model of design patterns and applications
What is design mode. A design pattern is a solution to a specific problem in a specific scenario, and these solutions are summed up through repeated demonstrations and tests. In fact, in addition to software design, design patterns are also widely used in other areas, such as UI design and architectural design.
The following is an introduction to the singleton pattern in design patterns in the cocoa touch framework.
Single-Case mode
The function of the singleton mode is to solve the problem of "only one instance in the application". In the cocoa touch framework, there are uiapplication, Nsuserdefaults, and Nsnotificationcenter and other singleton classes. In addition, although the Nsfilemanager and NSBundle classes are part of the cocoa framework, they can also be used in the Cocoa Touch Framework (cocoa, the Singleton class in the Nsworkspace and NSApplication, etc.).
Questions raised
In the life cycle of an application, sometimes only one instance of a class is needed. For example, when the iOS application starts, the state of the app is maintained by an instance of the UIApplication class, which represents the entire "Application Object", which can only be an instance of sharing some of the resources in the application, controlling access to the application, and maintaining the state of the application.
Solution Solutions
There are many options for the implementation of the singleton pattern, and Apple has given a single-case pattern implementation in the official document "Using Swift with Cocoa andobjective-c". The simplest form code is as follows:
Class Singleton {
Static letsharedinstance = Singleton ()
}
The code above uses the static class attribute to implement a singleton pattern, which is only executed once by deferred loading, even if it is performed only once in multithreaded situations and is guaranteed to be thread-safe.
If you need to do some initialization, you can use the following code with closures:
Class Singleton {
Static Letsharedinstance:singleton = {
Letinstance = Singleton ()
Initialization processing
Returninstance
}()
}
--cocoa Touch
Design Patterns and application objectives and actions
The Target and action (action) are medium event handling mechanisms for iOS and OS X app development.
There are two ways to achieve a connection between a target and an action: Interface Builder Connection implementation and programmatic implementation.
- Interface Builder Wiring Implementation
The Interface Builder connection is a storyboard or xib file that is wired and realistic.
- Programming implementation
The programming implementation is implemented through the Uicontrol class Addtarget (_:action:forcontrolevents:) method, the main code is as follows:
Class Viewcontroller:uiviewcontroller {
Override Func Viewdidload () {
Super.viewdidload ()
Self.view.backgroundcolor= Uicolor.whitecolor ()
Let screen = Uiscreen.mainscreen (). Bounds;
Let labelwidth:cgfloat= 90
Letlabelheight:cgfloat = 20
Letlabeltopview:cgfloat = 150
Let label = UILabel (Frame:cgrectmake (screen.size.width
-labelwidth)/2, Labeltopview,labelwidth, Labelheight))
Label.text = "Label"
Font left and right in the play
Label.textalignment =. Center
Self.view.addSubview (label)
Let button = UIButton (type:UIButtonType.System)//Create UIButton Object
Button.settitle ("OK", ForState:UIControlState.Normal)
Letbuttonwidth:cgfloat = 60
Letbuttonheight:cgfloat = 20
Letbuttontopview:cgfloat = 240
Button.frame = CGRectMake ((screen.size.width
-buttonwidth)/2, Buttontopview, Buttonwidth, Buttonheight)
Button.addtarget (Self, Action: "OnClick:",
ForControlEvents:UIControlEvents.TouchUpInside)
Self.view.addSubview (Button)
}
Func OnClick (sender:anyobject) {
NSLog ("OKButton onClick.")
}
...
}
The above code creates and sets the UIButton object, where the UIButton object is created, the parameter type is the style of the Set button, the UIButton style:
- Custom. The custom type. If you don't like the rounded button, you can use that type.
- System. System default property, which indicates that the button has no border, before iOS 7 the button defaults to a rounded rectangle.
- Detail Disclosure. Detail Display button, mainly used in the table view of the details of the display.
- Info Light and Info Dark. These two are informational buttons that, like the detail display buttons, indicate that there is some information that needs to be displayed, or something that can be set.
- ADD Contact. Add Contact button
- The code calls the Addtarget (_:action:forcontrolevents:) method, and the first parameter of the method is target, the event-handling object, in this case self; the second parameter of the method is the action, which is the method in the event-handling object.
The code is "OnClick:", the third parameter of the method is the event, and the Touchupinside event is a touch click event of the button.
If you call the following parameter-free method:
Func OnClick () {
}
The calling code is as follows:
Button.addtarget (Self, Action: "OnClick",
Êforcontrolevents:uicontrolevents.touchupinside)
The difference is that the action parameter "OnClick" method name differs, and the colon of the action parameter method name implies that the method name should have several parameters. If the method to be called is the following 3 parameter forms:
Func OnClick (Sender:anyobject, forevent event:uievent) {
}
Then the calling code is as follows:
Button.addtarget (Self, Action: "Onclick:forevent:",
Êforcontrolevents:uicontrolevents.touchupinside)
where "onclick:forevent:" is the calling method name, and the OnClick means that the method name is also, forevent represents the external parameter name for the second parameter.
--cocoa Touch
design pattern and application selector
To implement a target-to-action association using the Uicontrol class Addtarget (_:action:forcontrolevents:) method, the sample code is as follows:
Button.addtarget (Self, Action: "OnClick:",
ForControlEvents:UIControlEvents.TouchUpInside)
The action parameter "OnClick:" is actually the selector (Selector).
The method is called by the selector, the key is the method name, it has a certain regularity. The poor is rooted in the objective-c of the multiple parameter method named law. The colon of the method name implies that the method name should have several parameters, let's look at a few examples below:
The selector is "OnClick:"
Func OnClick (sender:anyobject) {
NSLog ("OnClick:")
}
Selector for "Onclick:forevent:"
Func OnClick (Sender:anyobject, forevent event:uievent) {
NSLog ("Onclick:forevent:")
}
Selector for "Onclickwithextsender:forevent:"
Func OnClick (Extsendersender:anyobject, forevent event:uievent) {
NSLog ("Onclickwithextsender:forevent:")
}
For the purposes of data encapsulation, we will add private to the method before it, and the code is as follows.
Private func OnClick (sender:anyobject) {
NSLog ("OnClick:")
}
However, the following error occurs when the method is called:
Unrecognized selector sent to instance 0X7F7F81499B10 '
This error means that the method specified by the selector is not found, that is, the OnClick: method is not found. It is a good practice to add the @objc attribute comment before the method, which means that the selector is called in the OBJC Runtime runtime environment.
The selector is "OnClick:"
@objc private Funconclick (sender:anyobject) {
NSLog ("OnClick:")
}
--cocoa Touch
notification mechanism of design pattern and application
The notification (Notification) mechanism is based on the Observer (Observer) pattern, also called the Publish/subscribe (Publish/subscribe) pattern, which is an important part of the MVC (model-View-controller) pattern.
In a software system, an object state change can also affect the state of many other objects. There are many design schemes to achieve this requirement, but the observer pattern is the most suitable one when it can be reused and anonymous communication between objects.
The notification mechanism can implement communication between "one-to-many" objects. , all objects that are interested in a notification in the notification mechanism can be recipients. First, these objects need to send a addobserver message to the Notification Center (nsnotificationcenter) for registration notice, in the delivery object through the POSTNOTIFICATIONNAME message delivery notification to the notification center, The Notification center will broadcast the notification to the registered recipient. All the recipients don't know who delivered the notification, and they don't care more about its details. The delivery object is a one-to-many relationship with the receiver. If the recipient is no longer concerned about the notification, the Notification center will be issued a REMOVEOBSERVER message cancellation notification, no longer receive notifications.
--cocoa Touch
the MVC pattern of design pattern and application
The MVC (Model-view-controller, model-View-Controller) pattern is one of the very old design patterns that first appeared in the Smalltalk language. Today, many computer languages and architectures use the MVC pattern.
MVC Pattern Overview
The MVC pattern is a composite design pattern, consisting of the observer (Observer) pattern, the Strategy (strategy) mode, and the composition (Composite) pattern. The MVC pattern consists of 3 parts, and the 3 parts are shown below.
· model . Save the status of the app data, respond to the view's status queries, process the application business logic, complete the application's functionality, and notify the view of changes in state.
· View . Present information to the user and provide an interface. The user makes an action request through the view to the controller, and then makes a request for the query state to the model, and the change in the model State is notified to the view.
· controller . Receives a user request and updates the model on request. In addition, the controller updates the selected view as a response to the user's request. The controller is the medium of the view and the model, can reduce the coupling degree of the view and the model, make the view and the model's responsibility more clear, thus improves the development efficiency.
Corresponding to the "content" and "form" in philosophy, in the MVC model, the pattern is "content", it stores the data that the view needs, the view is "form", is the external expression way, and the controller is their medium.
The MVC pattern in Cocoa touch
We're talking about the generic MVC pattern, and the MVC pattern in the cocoa and cocoa touch frameworks is slightly different from the traditional MVC pattern, where the model doesn't communicate with the view, and all communication is done through the controller.
In the Uikit framework of the cocoa Touch Framework, Uiviewcontroller is the root class for all controllers, such as Uitableviewcontroller, Uitabbarcontroller and Uinavigationcontroller. UIView is the root class for views and controls.
--cocoa Touch
Design Patterns and application of responder chains and touch events
The app interacts with the user and relies on a variety of events. An event responder object is an object that can respond to an event and process it, and the responder chain is made up of a series of linked respondents. The responder chain is very important in event handling, and the responder chain can be used
The correct object is routed to the user event.
Responder object and Response chain
Uiresponder is the base class for all responder objects, and it defines the programming interface not only for event handling, but also for common responder behavior. UIApplication, UIView (and their subclasses, including UIWindow) and Uiviewcontroller (and their subclasses) inherit from the Uiresponder class directly or indirectly.
The first responder is the responder object (usually a UIView object) in the application that is currently responsible for receiving touch events. The UIWindow object sends the event as a message to the first responder, giving it an opportunity to handle the event first. If the first responder does not process, the system passes the event (through the message) to the next responder in the responder chain to see if it can be processed.
The responder chain is a series of linked responder objects that allow the responder object to pass responsibility for handling events to other higher-level objects. As the application looks for objects capable of handling events, events are passed up in the responder chain. The responder chain consists of a series of "next responders".
1. The first responder passes the event to its view controller, if any, and then its parent view.
2. Similarly, each subsequent view in the view hierarchy is first passed to its view controller, if any, and then its parent view.
3. The topmost container view passes events to the UIWindow object.
4. The UIWindow object passes an event to the UIApplication singleton object.
Touch events
The Touch (Uitouch) object represents a touch event on the screen, and access to the touch is passed through the Uievent object to the Event responder object. Touch objects have both time and space.
1. Time aspects
The time aspect information is called the stage (phase), which indicates whether the touch has just begun, is moving or is in a stationary state, and when it ends, that is, when the finger is lifted from the screen.
In a given touch phase, the application sends these messages if a new touch action occurs or an existing touch action changes.
- Send touchesbegan:withevent: Message when one or more fingers touch the screen.
- Send touchesmoved:withevent: Message when one or more fingers move on the screen.
- Send touchesended:withevent: Message when one or more fingers leave the screen.
2. Space aspects
The touch point object also includes the current position information in the View or window, as well as the previous location information, if any. The following method is where you can get the position of the touch point in the window or view.
Func Locationinview (_view:uiview?), Cgpoint
Get location information in the window or view where the previous touch point is located:
Func Previouslocationinview (_ View:uiview?), Cgpoint
--swift
the language of mixed programming with Objective-c
Before the swift language appeared, developing iOS or OS X apps primarily used the Objective-c language, in addition to the C and C + + languages, but only the objective-c language was used in the UI section.
Select language
After the swift language appeared, Apple gave programmers more options to co-exist with each other. Since they coexist, there are 4 ways we can choose:
- Adopting the reform approach of pure swift;
- Adopt the Conservative way of pure objective-c;
- Using Swift to invoke Objective-c's left-leaning reformists mode;
- Use the objective-c to invoke Swift's right-leaning reformists mode.
File name extension
Tools such as Xcode to develop iOS or OS X apps can write multiple forms of source files that could have been used in the Objective-c, C, and C + + languages, and the Swift language appeared after the source file was more diverse. Potential file extension descriptions:
--swift
Swift and Objective-c API mapping with OBJECTIVE-C hybrid programmingSwift and OBJECTIVE-C API mapping
In the mixed programming process, swift and Objective-c call are bidirectional, because different languages for the same API expression is different, they have some kind of mapping law, the API mapping law is mainly embodied in the constructors and methods two aspects.
1. Constructor mapping
When Swift and Objective-c language are mixed programming, the first involves invoking the constructor instantiation object problem, different language constructs the function the expression form is different, is the Apple Company official API document, has described the NSString class the constructor function.
The Swift constructor in addition to the first argument, the external name of the other parameter is the selector counterpart part name. The other details of the law have been explained clearly, and the law is not the same.
2 , Method Name Mapping
In the mixed programming of Swift and Objective-c language, the method name representation is different in different languages, and it is Apple's official API document, which describes the RangeOfString:options:range: method of the NSString class.
The first part of the selector is rangeofstring as the method name, in general the external parameter name of the first parameter of the Swift method is to be omitted, and the "_" symbol means omitted. The name of each part of the selector, such as options and range, as the external parameter name. In addition to the parameter names, the argument types are also mapped.
After Swift2.0 the method can declare the throw error, these can throw the wrong method, different languages under the method name representation form, is writeToFile:atomically:encoding:error: Apple's official API document.
Comparing two different languages, we will find that the error parameter is no longer used in the swift language, but instead adds the throws keyword after the method.
This mapping rule is not only applicable to Apple's official Objective-c class, but also to the Objective-c class it has written.
--swift
data type mappings for mixed programming with C/
If you introduce the necessary header files, you can use the C data type in the Objective-c language. In the swift language, the C data type cannot be used directly, and Apple provides the swift language with the C language counterpart data type. These types mainly include: C language basic data types and pointer types.
The table describes the relationship table for the SWIFT data type and the C language base data type.
These data types in the swift language are essentially struct types, just like the swift native data type.
The table describes the relationship table for the SWIFT data type and the C language pointer data type.
Visible from the table for the C-language variety of pointer forms, swift mainly by providing three types of unsafe generic pointer type:unsafepointer<t>, unsafemutablepointer<t> and autoreleasingunsafemutablepointer<t>. T is a generic placeholder that represents a different data type. In addition, the Copaquepointer type is the C pointer type that cannot be represented in Swift.
Let's introduce the following separately.
- Unsafepointer<t>
Unsafepointer<t> is a more commonly used constant pointer type, which requires the programmer to manually manage the memory itself, that is, to request and free memory yourself. It is generally created by other pointers. Its main constructors are:
• init ( other:copaquepointer) . Created by the Copaquepointer type pointer.
init<u> ( from:unsafemutablepointer<u>). Created by the Unsafemutablepointer type pointer.
• init<u> (_ from:unsafepointer<u>). Created by the Unsafepointer type pointer.
Unsafepointer<t> Main properties:
• memory. A read-only property that accesses the content that the pointer points to.
Unsafepointer<t> Primary Method:
• successor (), Unsafepointer<t>. Gets the contents of the next memory address pointed to by the pointer.
• predecessor (), Unsafepointer<t>. Gets the contents of the previous memory address pointed to by the pointer.
- Unsafemutablepointer<t>
Unsafemutablepointer<t> is a more commonly used variable pointer type, which requires the programmer to manually manage the memory itself and is responsible for requesting and freeing the memory. A mutable pointer can be created by another pointer, or a mutable pointer can request memory space through Alloc (:) method, and then call Initialize (:) method initializes the pointer to a value. When the pointer object is released, it is necessary to call the Destroy () method to destroy the pointer to the object, which is the inverse of the Initialize (:) method, and the two methods in the code should appear in pairs. Finally, call Dealloc (the:) method releases the memory space pointed to by the pointer, which is the inverse of the Alloc (_:) method, and the two methods should appear in the code as well.
- Autoreleasingunsafemutablepointer<t>
Autoreleasingunsafemutablepointer<t> is called an auto-release pointer, declared in a method or function as a parameter of that type, is an input-output type, and in the process of invoking a method or function, the parameter is first copied to a non-ownership buffer. This buffer is used within a method or function, and when the method or function returns, the buffer data is re-written back to the parameter.
This is the basic note that I am learning swift to organize, hope to give more just learn iOS developer to bring help, here bloggers thank you very much for your support!
The basic swift Language basic notes have been sorted out here. If you feel that this blog is helpful to you, then move your little finger to a good point!! Haha, thank you bo friends for their support!!!
Learn Swift note finishing from 0 (Fri)