ios - 锁定 Objective-C 中的全类

标签 ios objective-c multithreading synchronized

我有一个非常简单的问题,希望有人能给我指出正确的方向。我是一名 Java 开发人员,试图找出全局锁的正确 Objective-C 方法。我有一个在多个地方实例化的类。每个实例读取和写入单个公共(public)文件。因此,我需要确保此类中的所有方法调用都是原子的。在 Java 中,这将按如下方式完成:

static Object lock

public void writeToFile(){
    synchronized(lock){
      //thread safe code goes here
    }
}

静态标识符意味着锁对象在所有实例之间共享,因此是线程安全的。不幸的是,由于 iOS 没有以同样的方式提供类变量,我不确定实现此功能的最佳方法是什么。

最佳答案

如果您想要的只是一个简单的全局锁,请查看 NSLock。

例如:

static NSLock * myGlobalLock = [[NSLock alloc] init];

if ([myGlobalLock tryLock]) {
    // do something
    [myGlobalLock unlock];
}
else {
    // couldn't acquire lock
}

但是,这会导致性能损失,因为它需要内核调用。如果您想序列化对资源的访问,使用 Grand Central Dispatch 和专用队列会执行得更好——这些都是在不需要内核中断的情况下进行调度的。

例如:

// alloc a dispatch queue for controlling access to your shared resource
static dispatch_queue_t mySharedResourceQueue = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    mySharedResourceQueue = dispatch_queue_create("com.myidentifier.MySharedResourceQueue", DISPATCH_QUEUE_SERIAL); // pick a unique identifier
});
// don't forget to call dispatch_release() to clean up your queue when done with it!

// to serialize access to your shared resource and block the current thread...
dispatch_sync(mySharedResourceQueue, ^{
    // access my shared resource
});

// or to access it asynchronously, w/o blocking the current thread...
dispatch_async(mySharedResourceQueue, ^{
    // access my shared resource
});

调度队列是非常了不起的东西,如果您要进入 iOS 开发,您应该学习如何使用它们来制作具有出色性能的应用程序。

除了 NSLock 之外,还有不同类型的锁。阅读线程编程引用中的同步以获取更多信息...

线程编程引用: https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Multithreading/Introduction/Introduction.html#//apple_ref/doc/uid/10000057i

NSLock 引用: https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSLock_Class/Reference/Reference.html

中央车站引用号:https://developer.apple.com/library/ios/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html

关于ios - 锁定 Objective-C 中的全类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17408607/

相关文章:

ios - SWRevealViewController - 管理 2 个不同的左侧菜单

ios - 如何在倒数计时器 Objective-C 中添加年份和月份

objective-c - 警告 : Unimplemented Selector localizedCaseInsensitiveCompare

javascript - IONIC是否支持多线程并调用Java开发的jar lib

wpf - 调用线程无法访问该对象,因为其他线程拥有它

ios - -[__NSCFString countByEnumerateWithState :objects:count:]: unrecognized selector sent to instance

ios - 当键盘出现在 iOS (Cordova) 上时如何调整 Web View 的大小

ios - 如何使用 UIViewPropertyAnimator 为 View 层阴影设置动画

ios - 如何在运行时增加 UITableview 中的行数?

android - 等待 TextToSpeech onInit() 初始化