I'm developing an iOS 5 and above with latest SDK.
我正在使用最新的SDK开发iOS 5及更高版本。
I have to implement a synchronized method with a Thread Lock
in Objective C.
我必须在Objective C中使用Thread Lock实现synchronized方法。
This is the Java version of what I have to do:
这是我必须做的Java版本:
public abstract class MyClass
{
[ ... ]
private static Object dataLock = new Object();
public static long dataId = 0;
[ ... ]
public static void PostData(byte[] data)
{
synchronized (MyClass.getDataLock())
{
dataId++;
MyClass.getDataLock().notify();
}
}
public static byte[] GetData()
{
synchronized (MyClass.getDataLock())
{
try
{
MyClass.getDataLock().wait();
}
catch (InterruptedException ex)
{}
return MyClass.getData();
}
}
[ ... ]
}
How do I implement dataLock
in Objective C? As a NSObject
?
How can I do PostData
and GetData
methods in Objective C?
如何在Objective C中实现dataLock?作为NSObject?如何在Objective C中执行PostData和GetData方法?
2 个解决方案
#1
3
Use the NSCondition
class. E.g.:
使用NSCondition类。例如。:
static NSCondition* g_dataLock = nil;
...
+ (void)initialize
{
if (self == [MyClass class])
{
g_dataLock = [NSCondition new];
}
}
+ (void)postData:(NSData*)data
{
[g_dataLock lock];
dataId++;
[g_dataLock signal];
[g_dataLock unlock];
}
+ (NSData*)getData
{
NSData* data = nil;
[g_dataLock lock];
[g_dataLock wait];
data = ...
[g_dataLock unlock];
return data;
}
See the Thread Programming Guide for more info.
有关详细信息,请参阅“线程编程指南”
#2
0
You can use @synchronized(dataLock){...code here...} but it's not the fastest way as described here.
您可以在这里使用@synchronized(dataLock){... code ...}但这不是这里描述的最快方式。
#1
3
Use the NSCondition
class. E.g.:
使用NSCondition类。例如。:
static NSCondition* g_dataLock = nil;
...
+ (void)initialize
{
if (self == [MyClass class])
{
g_dataLock = [NSCondition new];
}
}
+ (void)postData:(NSData*)data
{
[g_dataLock lock];
dataId++;
[g_dataLock signal];
[g_dataLock unlock];
}
+ (NSData*)getData
{
NSData* data = nil;
[g_dataLock lock];
[g_dataLock wait];
data = ...
[g_dataLock unlock];
return data;
}
See the Thread Programming Guide for more info.
有关详细信息,请参阅“线程编程指南”
#2
0
You can use @synchronized(dataLock){...code here...} but it's not the fastest way as described here.
您可以在这里使用@synchronized(dataLock){... code ...}但这不是这里描述的最快方式。