From b4e5bcf0cf840a4488027481e99a81f1ea5fa6da Mon Sep 17 00:00:00 2001 From: Nick Cooke <36927374+ncooke3@users.noreply.github.com> Date: Wed, 6 Nov 2024 16:49:21 -0500 Subject: [PATCH] [Config] Prefer NSLock over objc_sync_enter for synchronizing value types (#14041) --- .../SwiftNew/UserDefaultsManager.swift | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/FirebaseRemoteConfig/SwiftNew/UserDefaultsManager.swift b/FirebaseRemoteConfig/SwiftNew/UserDefaultsManager.swift index 8287b5c87c6..0e58d79a7bc 100644 --- a/FirebaseRemoteConfig/SwiftNew/UserDefaultsManager.swift +++ b/FirebaseRemoteConfig/SwiftNew/UserDefaultsManager.swift @@ -73,6 +73,7 @@ public class UserDefaultsManager: NSObject { } } + private static let sharedInstanceMapLock = NSLock() private static var sharedInstanceMap: [String: UserDefaults] = [:] /// Returns the shared user defaults instance for the given bundle identifier. @@ -81,14 +82,14 @@ public class UserDefaultsManager: NSObject { /// - Returns: The shared user defaults instance. @objc(sharedUserDefaultsForBundleIdentifier:) static func sharedUserDefaultsForBundleIdentifier(_ bundleIdentifier: String) -> UserDefaults { - objc_sync_enter(sharedInstanceMap) - defer { objc_sync_exit(sharedInstanceMap) } - if let instance = sharedInstanceMap[bundleIdentifier] { - return instance + sharedInstanceMapLock.withLock { + if let instance = sharedInstanceMap[bundleIdentifier] { + return instance + } + let userDefaults = UserDefaults(suiteName: userDefaultsSuiteName(for: bundleIdentifier))! + sharedInstanceMap[bundleIdentifier] = userDefaults + return userDefaults } - let userDefaults = UserDefaults(suiteName: userDefaultsSuiteName(for: bundleIdentifier))! - sharedInstanceMap[bundleIdentifier] = userDefaults - return userDefaults } /// Returns the user defaults suite name for the given bundle identifier.