Swift-core Foundation Framework-Preparation

Source: Internet
Author: User

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 very convenient to use the Corefoundation framework APIs during OS X and iOS development, for example in C language Mixed coding time.

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, and they can also be referred to as "classes", which are inherited from the Cftype class, andCftype is the Core The root class of the foundation framework type. 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:

[HTML]View PlainCopyprint?
  1. Import Corefoundation
  2. Import Foundation
  3. var cfstr1: cfstring = "Hello,world"//Create cfstring string
  4. var str: string = cfstr1 As String//Convert cfstring string to Swift native string string
  5. var cfstr2: cfstring = str//Convert Swift primitive string to cfstring string

The conversion of a Core Foundation type to a Swift native type is required to force type conversions during this transition.

During the conversion between the swift native data type, thefoundation framework data type, and the Core Foundation framework data type, although most of them can be zero overhead bridging, 0 overhead does not mean that memory is nothing. Swift type memory management is the use of arc,Foundation type and Core Foundation type memory management are either MRC or ARC, Corefoundation type memory management is based on the C language style, and it has a concept of object ownership.

MRC Memory management for OBJECTIVE-C

The memory management of Core Foundation is inseparable from Objective-c's MRC memory management, 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, Referred to as RC). When the object is created, the reference count is 1. To guarantee the existence of the object, you can call the retain method to persist the object, and theretain method will make its reference count plus 1, 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.

Example of a reference count, first at the ① pace userA has been created in aNSObject object, at which point the object reference is counted as1. In the ② step user b want to use this nsobject object, so use nsobject object reference, but in order to prevent the use of the process nsobject object is released, you can call retain method to make the reference count plus 1, when the reference count is 2. Call release or autorelease method in the ③ user a to reduce the reference count 1, the reference count is 1. The release or autorelease method is called in the ④ c, only to obtain nsobject object reference, and did not call retain, release or The Autorelease method does not cause a change in the reference count. Call release or autorelease method in the ⑤ user b to reduce the reference count 1, the reference count is 0. At this time nsobject object can be freed up by memory.

To summarize:

1. 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 the creation of the NSObject object, Then caller A must also be responsible for reducing the reference count by 1, see step ④.

2. 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 the caller B uses this NSObject object procedure, The program in caller B will have a run-time error because the other caller abandons ownership and causes the NSObject object to be disposed .

======================

Memory managed Objects

When you call the corefoundation function in Swift to get an object, the object is divided into: Memory managed objects and memory unmanaged 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 Comment Declaration, the sample code:

[HTML]View PlainCopyprint?
  1. -(CGPATHREF) Maketopath cf_returns_retained
  2. {
  3. uibezierpath* triangle = [Uibezierpath Bezierpath];
  4. [Triangle Movetopoint:cgpointzero];
  5. [Triangle Addlinetopoint:cgpointmake (self.view.frame.size.width,0)];
  6. [Triangle Addlinetopoint:cgpointmake (0, Self.view.frame.size.height)];
  7. [Triangle Closepath];
  8. Cgpathref Thecgpath = [triangle Cgpath];
  9. Return cgpathcreatecopy (Thecgpath);
  10. }

Memory managed objects are simple to use and do not require us to do extra things.

[HTML]View PlainCopyprint?
  1. Func cfstringcreatewithcstring (_ alloc:cfallocator!,
  2. _ Cstr:unsafepointer<Int8;
  3. _ encoding:cfstringencoding)-> cfstring! Memory Managed Objects
  4. Func Cfhostcreatecopy (_ Alloc:cfallocator?,
  5. _ Host:cfhost)-> unmanaged<cfhost>//Memory unmanaged Objects


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.

1. If a function name contains Create or Copy, the caller obtains the object ownership at the same time, and the return value unmanaged<t> needs to call Takeretainedvalue () method to obtain the object. When the caller no longer uses the object, theSwift code needs to call the cfrelease function to discard the object ownership, because Swift is managed by arc memory.

2. If a function name contains a get, the caller obtains the object without taking ownership of the object, and the return value unmanaged<t> calls the Takeunretainedvalue () method to obtain the object.

The sample code is as follows:

[HTML]View PlainCopyprint?
      1. Let host: cfhost = cfhostcreatewithname (kcfallocatordefault,
      2. Ê "127.0.0.1"). Takeretainedvalue ()
      3. Let hostnames: Cfarray = cfhostgetnames (host, nil)!. Takeunretainedvalue ()

Swift-core Foundation Framework-Preparation

Related Article

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.