objective-c - Swift 变量是原子的吗?

标签 objective-c swift

在 Objective-C 中,原子属性和非原子属性是有区别的:

@property (nonatomic, strong) NSObject *nonatomicObject;
@property (atomic, strong) NSObject *atomicObject;

据我了解,您可以从多个线程安全地读取和写入定义为原子的属性,而同时从多个线程写入和访问非原子属性或 ivar 可能会导致未定义的行为,包括错误的访问错误。

所以如果你在 Swift 中有这样一个变量:

var object: NSObject

我可以安全地并行读写这个变量吗? (不考虑这样做的实际意义)。

最佳答案

现在假设没有可用的低级文档还为时过早,但您可以从汇编学习。 Hopper Disassembler是一个很棒的工具。

@interface ObjectiveCar : NSObject
@property (nonatomic, strong) id engine;
@property (atomic, strong) id driver;
@end

对非原子和原子分别使用objc_storeStrongobjc_setProperty_atomic,其中

class SwiftCar {
    var engine : AnyObject?    
    init() {
    }
}

使用 libswift_stdlib_core 中的 swift_retain 并且显然没有内置线程安全。

我们可以推测稍后可能会引入其他关键字(类似于 @lazy)。

2015 年 7 月 20 日更新:根据此 blogpost on singletons swift 环境可以使某些情况对您来说是线程安全的,即:

class Car {
    static let sharedCar: Car = Car() // will be called inside of dispatch_once
}

private let sharedCar: Car2 = Car2() // same here
class Car2 {

}

2016 年 5 月 25 日更新:密切关注快速进化提案 https://github.com/apple/swift-evolution/blob/master/proposals/0030-property-behavior-decls.md - 看起来可以让 @atomic 行为由你自己实现。

关于objective-c - Swift 变量是原子的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41058811/

相关文章:

c - 如何以编程方式获取 mac os x macbooks 的电池生命周期?

iOS : -[__NSCFDictionary _expandedCFCharacterSet]: error

iphone - 在 iPhone 上以编程方式测量网络流量

ios - Alamofire json 请求失败

ios - 在 SwiftUI 中使用分段式选取器在两个页面之间滑动

swift - 数组未在 Swift 中更新

objective-c - 如何交换big 到主机int8 数字?

iOS - UINavigationController,隐藏导航栏

swift - didSelectRowAt : IndexPath is not working and will not print to the console when the cell pressed on

swift - 在 tvos 中播放系统声音 [swift]