swit3.1 (9)笔记 内存管理和方法

Transitioning to ARC Release Notes(oc内存管理)

https://developer.apple.com/library/content/releasenotes/ObjectiveC/RN-TransitioningToARC/Introduction/Introduction.html#//apple_ref/doc/uid/TP40011226

1、__strong is the default. An object remains “alive” as long as there is a strong pointer to it.

强引用是默认的,一个对象只有有一个强指针指向它,它就依然存活。

2、Under ARC, strong is the default for object types.

使用arcstrong是你默认使用的类型。

3__unsafe_unretained specifies a reference that does not keep the referenced object alive and is not set to nil when there are no strong references to the object. If the object it references is deallocated, the pointer is left dangling.

 当没有对这个对象的强引用的时候,__unsafe_unretained指定这个引用,这个引用就会让这个引用的对象失活,然后被设置为空。如果它引用的对象被释放了,那么这个指针就会摇摆在哪里成为僵尸指针。

dangling 悬挂的,摇摆的

4、__autoreleasing is used to denote arguments that are passed by reference (id *) and are autoreleased on return.

denote表示,指示

__autoreleasing 被用来表示通过id *传递过来的参数,在return上自动释放。

5、variable qualifiers 变量限制符号

6、using qualitiers in an object varable declaration,the correct format is :

ClassName * qualifier variableName

MyClass * __weak myWeakRefence

MyClass * __unsafe_unretained myUnsafeReference

7、Other variants are technically incorrect but are “forgiven” by the compiler.

其他变量是技术上不正确的,会被编译器谅解


swift内存管理

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-ID52


1The main exception to this rule occurs when a parameter name for an instance method has the same name as a property of that instance.

这条规则的主要的例外就是当实例变量的参数名字跟实例的属性有一个相同的属性的时候(就必须加上那个self)

2、Structures and enumerations are value typesBy default, the properties of a value type cannot be modified from within its instance methods。

结构和枚举是值类型,在默认上,一个值类型的属性不能从他的实例方法的内部来修改。

3if you need to modify the properties of your structure or enumeration within a particular method, you can opt in tomutating behavior for that method。

如果你需要在一个特殊的方法里面修改你的结构或者枚举的属性,你能为那个方法选择可变的行为。

4、You can opt in to this behavior by placing themutating keyword before thefunc keyword for that method:


struct Point {

  •    varx =0.0,y =0.0
  •    mutating  funcmoveBy(xdeltaX:Double,ydeltaY:Double) {
  •        x +=deltaX
  •        y +=deltaY
  •     }
  • }
  • varsomePoint =Point(x:1.0,y:1.0)
  • somePoint.moveBy(x:2.0,y:3.0)
  • print("The point is now at (\(somePoint.x),\(somePoint.y))")
  • // Prints "The point is now at (3.0, 4.0)"

5、The method can also assign a completely new instance to its implicitself property, and this new instance will replace the existing one when the method ends.

AAAAAA

6、Note that you cannot call a mutating method on a constant of structure type, because its properties cannot be changed, even if they are variable properties

注意你不能在一个结构类型常量调用一个可变的方法,即使他们是变量属性。

7、This version of the mutatingmoveBy(x:y:) method creates a brand new structure whosex andy values are set to the target location. The end result of calling this alternative version of the method will be exactly the same as for calling the earlier version.AAAAAAA

8You indicate type methods by writing the static keyword before the method’sfunc keyword. Classes may also use theclass keyword to allow subclasses to override the superclass’s implementation of that method.

你通过在func关键字前写static关键字实现这些方法(类方法type method),类也许可以用类class关键字来来允许子类重写父类的实现。

9、Each type(type method) method is explicitly scoped to the type it supports.

每个方法被局限于它支持的类型。

10you call type methods on the type

你通过类型调用类方法

  • classSomeClass {
  •    classfuncsomeTypeMethod() {
  •        // type method implementation goes here
  •     }
  • }
  • SomeClass.someTypeMethod()

11Within the body of a type method, the implicitself property refers to the type itself, rather than an instance of that type

在类方法实体内部,self属性指类型它自己,而不是类型的实例。

12、More generally, any unqualified method and property names that you use within the body of a type method will refer to other type-level methods and properties. A type method can call another type method with the other method’s name, without needing to prefix it with the type name

通常的,任何你在类型方法实现体里面使用的没限制的方法和属性名字将指向其他同水平的方法和属性,一个类型方法能通过用其他方法的名字来调用另一个另行方法,不需要用类型名字加前缀,

13、Similarly, type methods on structures and enumerations can access type properties by using the type property’s name without a type name prefix.

同样的,在结构和枚举上的类型方法通过使用类型属性的名字能接近类型的属性,不需要类型名字前缀。(方法那边还有一点没弄好)

14、


subscripts

1、You can define multiple subscripts for a single type, and the appropriate subscript overload to use is selected based on the type of index value you pass to the subscript. Subscripts are not limited to a single dimension, and you can define subscripts with multiple input parameters to suit your custom type’s needs.

你可以给一个简单的类型定义多个下标。AAAAA。下表不限于一个简单的范围,你能用多个输入参数定义下标来满足你定制的类型需要。

2、You write subscript definitions with thesubscript keyword, and specify one or more input parameters and a return type, in the same way as instance methods.

你用subscript关键字写下标定义,制定一个或者更多输入参数和一个返回类型,以一种实例方法的方式。

3、Unlike instance methods, subscripts can be read-write or read-only. This behavior is communicated by a getter and setter in the same way as for computed properties:

不像实例方法,下标注能是读写的或者只读的,这种行为通过一个getter或者setter来沟通,类似于计算属性。

4、subscript(index:Int) ->Int {

  •    get {
  •        // return an appropriate subscript value here
  •     }
  •    set(newValue) {
  •        // perform a suitable setting action here
  •     }
  • }

5As with computed properties, you can choose not to specify the setter’s(newValue) parameter. A default parameter callednewValue is provided to your setter if you do not provide one yourself.

就像计算属性,你可以选择不要制定 setter的参数,如果你没有提供一个给自己,一个叫newValue的参数被提供给你的setter。

6、As with read-only computed properties, you can simplify the declaration of a read-only subscript by removing theget keyword and its braces:

  • subscript(index:Int) ->Int {
  •    // return an appropriate subscript value here
  • }

就像只读的计算属性,你可以通过移除get关键字和它的括号来制定一个只读下标的声明。

7、Subscripts can take any number of input parameters, and these input parameters can be of any type. Subscripts can also return any type. Subscripts can use variadic parameters, but they can’t use in-out parameters or provide default parameter values.

下标能采用任何数量的输入参数,二这些输入参数能是任何类型,下标也能是任何类型,下标能用变化的参数,但是他们不能用输入输出的参数或者提供默认的参数值。

8、and the appropriate subscript to be used will be inferred based on the types of the value or values that are contained within the subscript brackets at the point that the subscript is used

当下标在使用的时候,将被使用的合适的下标能被推断出来,这基于包含在下标括号里面的值和很多值得类型。


automatic reference counting

自动引用计数

1、ARC automatically frees up the memory used by class instances when those instances are no longer needed.

当这些实例不再使用的时候,arc自动释放被类实例使用的内存。

2、However, in a few cases ARC requires more information about the relationships between parts of your code in order to manage memory for you

然而,在一些案例中,arc需要你代码部分之间的关系,以便来为你管理内存。

3、Reference counting only applies to instances of classes. Structures and enumerations are value types, not reference types, and are not stored and passed by reference.

引用计数唯一应用于类的实例,结构体和枚举是值类型,不是引用类型,不通过reference存值或者传值。

4、Every time you create a new instance of a class, ARC allocates a chunk of memory to store information about that instance. This memory holds information about the type of the instance, together with the values of any stored properties associated with that instance.

每当你创建一个类的新的实例的时候,arc开辟一块内存来存储那个实例的信息,这个内存持有那个实例的类型,以及与那个实例相关的任何存取属性。

5However, if ARC were to deallocate an instance that was still in use, it would no longer be possible to access that instance’s properties, or call that instance’s methods. Indeed, if you tried to access the instance, your app would most likely crash.

然而,如果ARC将去释放一个仍在使用的实例,那么那个实例不可能再去接近实例的属性,或者调用实例的方法,确实,如果你尝试去接近那个实例,你的app就可能崩溃。

6、To make sure that instances don’t disappear while they are still needed, ARC tracks how many properties, constants, and variables are currently referring to each class instance. ARC will not deallocate an instance as long as at least one active reference to that instance still exists.

为了确保实例在他们扔被需要不消失,ARC追踪很多属性,常量,变量目前是怎么引用这个实例的。只要至少有一个对实例的活跃的引用在,arc就不会释放那个实例。

7、To make this possible, whenever you assign a class instance to a property, constant, or variable, that property, constant, or variable makes astrong reference to the instance. The reference is called a “strong” reference because it keeps a firm hold on that instance, and does not allow it to be deallocated for as long as that strong reference remains.

为了让这实现,无论什么时候,你给一个类实例赋值一个属性,常量或者变量,那个属性,常量,变量对那个实例有一个强引用,这个引用之所以叫做强引用是因为它(属性,常量或者变量)对那个实例有一个强力的持有,这个引用不允许实例被释放,只要那个强引用还在。

8、Because these variables are of an optional type (Person?, notPerson), they are automatically initialized with a value ofnil, and do not currently reference aPerson instance.

因为这些变量是一个选择类型,他们被自动初始化为nil,没有对Person实例对象进行引用。

9、Strong Reference Cycles Between Class Instances

在类实例之间的强引用循环。

10This can happen if two class instances hold a strong reference to each other, such that each instance keeps the other alive. This is known as astrong reference cycle.

这常常发生,如果两个类的实例对另一个有一个强引用,这样,每个实例让另一个存活。

11、You resolve strong reference cycles by defining some of the relationships between classes as weak or unowned references instead of as strong references. 

若引用循环和非拥有循环。

12、Therefore, when you break the strong references held by thejohn andunit4A variables, the reference counts do not drop to zero, and the instances are not deallocated by ARC:

  • john = nil
  • unit4A =nil
  • AAAA

13Swift provides two ways to resolve strong reference cycles when you work with properties of class type: weak references and unowned references.

swift提供两种方式来分解循环引用:若引用,以及非拥有引用。

14、Use a weak reference when the other instance has a shorter lifetimeIn contrast, use an unowned reference when the other instance has the same lifetime or a longer lifetime.

当其他实例有一个更短的生命周期使用一个若引用循环,对比之下,当其他实例有一个相同的生命周期或者一个更短的生命周期的时候,使用一个非拥有的引用。

15、you indicate a weak reference by placing theweak keyword before a property or variable declaration.

你显示一个若引用循环,通过在一个属性或者变量声明前放一个weak关键字。

16、because weak references need to allow their value to be changed tonil at runtime, they are always declared as variables, rather than constants, of an optional type.

因为weak 引用循环需要允许他们的值在运行时中被改变成nil,他们总是被声明为变量,而不是常量或者选择类型。

17ThePerson instance still has a strong reference to theApartment instance, but the Apartment instance now has aweak reference to thePerson instance. This means that when you break the strong reference held by thejohn variable by setting it tonil, there are no more strong references to thePerson instance:

Because there are no more strong references to thePerson instance, it’s deallocated and thetenant property is set tonil:

为什么不能设置为nil,当你设置的时候,另一个在强引用它,nil实现不了。

18In systems that use garbage collection, weak pointers are sometimes used to implement a simple caching mechanism because objects with no strong references are deallocated only when memory pressure triggers garbage collection. However, with ARC, values are deallocated as soon as their last strong reference is removed, making weak references unsuitable for such a purpose.



在应用垃圾回收装置的系统,弱指针通常被用来实现一个简单的缓存装置,因为没有强引用的的对象只有在内存压力触发垃圾装置的时候才会被释放,然后,在arc,一般他们最后的强引用移除,值立即被释放,AAAA

19、You indicate an unowned reference by placing theunowned keyword before a property or variable declaration.

你声明一个非拥有引用,通过放一个unowned关键字。

20Use an unowned reference only when you are sure that the referencealways refers to an instance that has not been deallocated.

If you try to access the value of an unowned reference after that instance has been deallocated, you’ll get a runtime error.

一个非拥有的引用只有使用在你确保那个引用指向一个没有被释放的值。

如果你尝试靠近一个非拥有的值,而那个值之前就已经释放了,你将会得到一个运行时错误。

21、These two classes each store an instance of the other class as a property. This relationship has the potential to create a strong reference cycle.

这两个类各自存储其他类的属性作为属性,这种关系有潜力创造一个强引用循环。

22、the relationship betweenCustomer andCreditCard is slightly different from the relationship betweenApartment andPerson seen in the weak reference example above. In this data model, a customer may or may not have a credit card, but a credit card willalways be associated with a customer.

在客户和信用卡的关系中不同于若引用循环的关系的公寓和人的关系,在这个数据模型中,一个客户有或者没有一个信用卡,但是一个积分卡总是跟一个客户有关联。

23、A CreditCard instance never outlives theCustomer that it refers to. To represent this, theCustomer class has an optional card property, but theCreditCard class has an unowned (and nonoptional)customer property.

一个积分卡实例从不比它指向的客户活的更长,为了表示这种关系,客户类有一个选择性的card属性(可以为nil),但是积分卡类非拥有(非选择性)的客户属性。

24、The examples above show how to usesafe unowned references. Swift also providesunsafe unowned references for cases where you need to disable runtime safety checks—for example, for performance reasons. As with all unsafe operations, you take on the responsiblity for checking that code for safety.

You indicate an unsafe unowned reference by writingunowned(unsafe). If you try to access an unsafe unowned reference after the instance that it refers to is deallocated, your program will try to access the memory location where the instance used to be, which is an unsafe operation.


以上例子展示了怎么用安全的非拥有引用,swift也提供unsafe unowned引用,这些条件下,你需要废弃运行时安全检查,举个例子,在某些为了性能的条件下(你可能会用这个非安全的,其实安全的就是runtim系统为你做了安全检查)对于所有非安全操作,你负责检查那些代码的安全。你通过写一个unowned(unsafe)关键字来展示一个非安全非拥有的引用,如果在引用指向的实例被释放后,你再尝试接近那个非安全非拥有的引用,你的项目将尝试靠近那些以前实例过去在的内存区,但这是一个不安全的操作。

25、The Person andApartment example shows a situation where two properties, both of which are allowed to benil, have the potential to cause a strong reference cycle. This scenario is best resolved with a weak reference.

两个属性都可以为空

26、The Customer andCreditCard example shows a situation where one property that is allowed to benil and another property that cannot benil have the potential to cause a strong reference cycle. This scenario is best resolved with an unowned reference.

两个其中一个可以为空,另一个不能

27、However, there is a third scenario, in whichboth properties should always have a value, and neither property should ever benil once initialization is complete

两个属性都不能为空的情形。

28In this scenario, it’s useful to combine an unowned property on one class with an implicitly unwrapped optional property on the other class.

在这个章节中,在一个类中用一个unowned属性,但是在另一个类中用一个模糊的拆包的选择性属性。

<这个第三种情形还需继续深究>

29、Strong Reference Cycles for Closures闭包的强引用

A strong reference cycle can also occur if you assign a closure to a property of a class instance, and the body of that closure captures the instance. 

一个强引用会发生,如果你将一个闭包赋值=给一个类实例的属性,二这个闭包的实体有引用了这个实例的时候。

30、This capture might occur because the closure’s body accesses a property of the instance, such asself.someProperty, or because the closure calls a method on the instance, such asself.someMethod(). In either case, these accesses cause the closure to “capture”self, creating a strong reference cycle.

self.property 或者self.method都是符合captue情形。

31You resolve a strong reference cycle between a closure and a class instance by defining acapture list as part of the closure’s definition.

你可以通过定义一哥俘获系列作为闭包定义的一部分来解决这个循环引用的问题。

32、为什么双循环引用不可释放,如果你对其中一个A设为nil,系统会说,不行另一个B还对你有引用,同样,如果我将B设为niL,系统同样会说那样的话。但是,单引用,比如A引用B,因为A不受羁绊,A可以设为nil,A设为nil,系统对B的引用将为零,它也释放。但是如果A引用B我们事先就将B释放,但是A也会跟着变为nil,这个不违法。

33、Swift requires you to writeself.someProperty orself.someMethod() (rather than justsomeProperty orsomeMethod()) whenever you refer to a member ofself within a closure. This helps you remember that it’s possible to captureself by accident.


当你在闭包内部的时候,swift强制要求你写self去接近的成员变量。

34、Place the capture list before a closure’s parameter list and return type if they are provided:

  • lazyvarsomeClosure: (Int,String) ->String = {
  •     [unownedself,weakdelegate =self.delegate!] (index:Int,stringToProcess:String) ->Stringin
  •    // closure body goes here
  • }

These pairings are written within a pair of square braces, separated by commas.

这些对写在一个方括号里面,用逗号分开。

35、If a closure does not specify a parameter list or return type because they can be inferred from context, place the capture list at the very start of the closure, followed by thein keyword:

  • lazyvarsomeClosure: () ->String = {
  •     [unownedself,weakdelegate =self.delegate!]in
  •    // closure body goes here
  • }


如果一个闭包没有指定一个参数列表或者返回类型,因为他们都可以从上下文推断出来,将俘获列表放在在最开端,后面加一个in关键字。

36、If the captured reference will never becomenil, it should always be captured as an unowned reference, rather than a weak reference.

如果俘获引用将从不变为nil,她将总是被俘获作为一个非拥有引用,而不是一个若引用。

37Define a capture in a closure as an unowned reference when the closure and the instance it captures will always refer to each other, and will always be deallocated at the same time.

Conversely, define a capture as a weak reference when the captured reference may becomenil at some point in the future. Weak references are always of an optional type, and automatically becomenil when the instance they reference is deallocated. This enables you to check for their existence within the closure’s body.



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值