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

在 Objective-C 中,您可以区分原子属性和非原子属性:

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

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

所以如果你在 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 行为。

https://stackoverflow.com/questions/24157834/

相关文章:

objective-c - ViewController 响应选择器 : message sent

iphone - 如何拦截点击 UITextView 中的链接?

objective-c - 按名称创建objective-c类实例?

ios - 获取当前页面

ios - 横向模式下的 iPhone 应用程序,2008 系统

objective-c - 数字后的 "f"

objective-c - 如何在 Xcode 中定义预处理器符号

objective-c - 在Objective-C中将一个类的实例转换为@protocol

iphone - Xcode 调试器 : view value of variable

objective-c - 无法使用 nil 模型创建 NSPersistentStoreCoord