swift中的全局变量不会改变

时间:2015-03-28 10:12:40

标签: ios swift global-variables

我为我的应用创建了几个全局变量来加载图像和字符串。当我尝试改变它时,它们保持不变。在调用didSelectRowAtIndexPath方法之后,该值仍然没有变化,它仍然是" initial"。

import UIKit

var testString = "initial"

class SubjectsViewController: UIViewController {

.....

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

        imageFiles[indexPath.row].getDataInBackgroundWithBlock { imageData, error in
            if (error == nil) {
                selectedPhoto = UIImage(data: imageData)!
                println("Should change variables")
                testString = "testing"
                println("no error in fetching image")
            } else {
                println("There is an error getting image")
            }
        }

        self.performSegueWithIdentifier("detailSegue", sender: self)
    }

1 个答案:

答案 0 :(得分:0)

创建一个包含应用程序的所有全局变量的类

 class GlobalVariables : NSObject {
       var testString = "initial"
    }
    var global = GlobalVariables()

所以现在你的班级使用代码

 if (error == nil) {
                selectedPhoto = UIImage(data: imageData)!
                println("Should change variables")
// Global variable as now this will work and its value will be not be remove until the application is close , and change until y             
                global.testString = "testing"
                println("no error in fetching image")