Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/104.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 保留应用程序执行期间生成的随机数,直到应用程序以Swift方式退出_Ios_Swift - Fatal编程技术网

Ios 保留应用程序执行期间生成的随机数,直到应用程序以Swift方式退出

Ios 保留应用程序执行期间生成的随机数,直到应用程序以Swift方式退出,ios,swift,Ios,Swift,我写了一个函数代码来生成随机数 func randomNumGenerate() -> Int { let formatter = DateFormatter() formatter.dateFormat = "HHmmss" let currentTimeStr = formatter.string(from: Date()) return Int(currentTimeStr) ?? 0 } 然后使用此数字运

我写了一个函数代码来生成随机数

func randomNumGenerate() -> Int {
        let formatter = DateFormatter()
        formatter.dateFormat = "HHmmss"

        let currentTimeStr = formatter.string(from: Date())

        return Int(currentTimeStr) ?? 0
    }
然后使用此数字运行另一个类函数

    override func viewDidLoad() {
        super.viewDidLoad()

        BookAPI.requestGenre(bookGenre: 13, bookAddPoint: bookAddPoint, randomSeed: randomNumGenerate(), completionHandler: handleBooksGenre(books:error:))

    }

当执行class函数时,由于生成了
randomNumGenerate()
编号,所以
bookGenre:13
的数据被随机排序

但问题是,当我转到另一个viewController,然后再次使用上述函数返回viewController时,数字会随机生成,对齐方式也会改变


如何保持应用程序运行时生成的随机数直到应用程序退出?

一种方法是在应用程序启动后,在
applicationdFinishLaunching
中生成随机数:

// AppDelegate.swift
var randomNumber: Int!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    randomNumber = randomNumGenerate()
    return true
}
这确保每次发射只生成一个随机数

然后在VC中,访问以下随机数:

let randomNumber = (UIApplication.shared.delegate as! AppDelegate).randomNumber
BookAPI.requestGenre(
    bookGenre: 13, 
    bookAddPoint: bookAddPoint, 
    randomSeed: randomNumber, 
    completionHandler: handleBooksGenre(books:error:))

这个随机数不是那么随机的。它将每天每秒重复。我不能保留应用程序运行时生成的currentTimeStr吗?您可以在视图控制器类中为其创建一个属性,并将该值分配给该属性<代码>书籍类型:Int