快速的二传手导致exc_bad_access [英] swift setter causing exc_bad_access

查看:78
本文介绍了快速的二传手导致exc_bad_access的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面有一个简单的课程

I have a simple class below

import Foundation

public class UsefulClass: NSObject{
    var test:NSNumber{
        get{return self.test}
        set{
            println(newValue)
            self.test = newValue
        }
    }
    override init() {
        super.init()
        self.test = 5;
    }
}

我在这里初始化它

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        var testClass = UsefulClass()
    }
}

但是它会导致xcode打印出200 5s,然后由于EXC_BAD_ACCESS code = 2而崩溃.为什么会发生这种情况?

But it results in xcode printing out 200 5s and then crashing due to EXC_BAD_ACCESS code = 2. Why does this happen?

推荐答案

@vadian在他的回答中提供了一个解决方案,它可以解决您的问题.让我解释一下发生了什么.

@vadian has provided a solution in his answer, which should fix your problem. Let me just explain what's happening.

您已经创建了一个计算属性,即一个没有变量支持的属性,取而代之的是,getter和setter都通常在另一个存储的属性上进行一些处理,以便分别返回一个值并设置一个新值

You have created a computed property, i.e. a property which is not backed by a variable, instead both the getter and the setter do some processing, usually on another stored property, in order to respectively return a value and set a new value.

这是您计算出的属性:

var test: NSNumber {
    get { return self.test }
    set {
        println(newValue)
        self.test = newValue
    }
}

看看getter的实现:

Look at the getter implementation:

return self.test

它是做什么的?它读取当前实例的test属性,并返回它. test属性是哪个?就是这个:

What does it do? It reads the test property of the current instance, and returns it. Which is the test property? It's this one:

var test: NSNumber {
    get { return self.test }
    set {
        println(newValue)
        self.test = newValue
    }
}

是的,它是相同的属性.您的getter所做的就是递归和无限期地自我调用,直到在运行时发生崩溃为止.

Yes, it's the same property. What your getter does is to recursively and indefinitely calling itself, until a crash happen at runtime.

相同的规则适用于二传手:

The same rule applies to the setter:

self.test = newValue 

它会不断调用自身,直到应用程序崩溃为止.

it keeps invoking itself, until the app crashes.

这篇关于快速的二传手导致exc_bad_access的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆