编写多线程应用程序时,遇到的最常见问题之一是竞争条件.
我对社区的问题是:
什么是比赛条件?你怎么发现它们?你怎么处理它们?最后,你如何防止它们发生?
我的单例访问器方法通常是以下的一些变体:
static MyClass *gInstance = NULL;
+ (MyClass *)instance
{
@synchronized(self)
{
if (gInstance == NULL)
gInstance = [[self alloc] init];
}
return(gInstance);
}
Run Code Online (Sandbox Code Playgroud)
我可以做些什么来改善这个?
在接口的实现中定义时,我不太了解静态变量.在方法中,我确实理解它们与局部变量的区别,但不是直接在实现中定义的.
看看这些例子.这两者实际上有什么区别?
#include "MyClass.h"
@implementation MyClass
int myInt;
...
@end
Run Code Online (Sandbox Code Playgroud)
和:
#include "MyClass.h"
@implementation MyClass
static int myInt;
...
@end
Run Code Online (Sandbox Code Playgroud)
myInt在两种情况下,所有方法都可以看到,如果我解释了一个正确运行的测试,那么myInt在这两种情况下,对于不同类的实例,它们都是相同的变量.
我的iOS应用程序只是崩溃与NSRangeException上-[NSManagedObjectContext save:].在任何地方找不到任何其他帮助.我该如何解决这个问题?我没有任何内存地址或任何我可以使用的内容......
2015-04-22 14:16:38.078 heavenhelp[33559:1734247] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 6 beyond bounds [0 .. 5]'
*** First throw call stack:
(
0 CoreFoundation 0x0167f746 __exceptionPreprocess + 182
1 libobjc.A.dylib 0x00f40a97 objc_exception_throw + 44
2 CoreFoundation 0x01553b73 -[__NSArrayM objectAtIndex:] + 243
3 CoreData 0x00859cf3 -[NSSQLCore recordToManyChangesForObject:inRow:usingTimestamp:inserted:] + 2531
4 CoreData 0x00856a0b -[NSSQLCore _populateRow:fromObject:timestamp:inserted:] + 2923
5 CoreData 0x00776e24 -[NSSQLCore prepareForSave:] + 1764
6 CoreData 0x00775e3d -[NSSQLCore saveChanges:] + …Run Code Online (Sandbox Code Playgroud) 我看到了线程安全的版本
+(MyClass *)singleton {
static dispatch_once_t pred;
static MyClass *shared = nil;
dispatch_once(&pred, ^{
shared = [[MyClass alloc] init];
});
return shared;
}
Run Code Online (Sandbox Code Playgroud)
但如果有人打电话[MyClass alloc] init]会怎么样?如何让它返回与+(MyClass *)singleton方法相同的实例?
我有一个带有几个控制器的iOS应用程序,每个控制器都有自己的xib文件.
如何设置一个跨越所有控制器的范围的全局变量?我应该NSUserDefaults每次都为每个视图使用和检索数据吗?
我创建了一个单例类来跟踪我的iPhone应用程序上的数据.我知道singleton只需要实例化一次,但实例化它的最佳位置是什么?应该在appDelegate中完成吗?我希望能够从众多类中调用此单例(包含NSMutableArray),以便我可以访问该数组.
这是我写的课程:
#import "WorkoutManager.h"
static WorkoutManager *workoutManagerInstance;
@implementation WorkoutManager
@synthesize workouts;
+(WorkoutManager*)sharedInstance {
if(!workoutManagerInstance) {
workoutManagerInstance = [[WorkoutManager alloc] init];
}
return workoutManagerInstance;
}
-(id)init {
self = [super init];
if (self) {
workouts = [[NSMutableArray alloc] init];
}
return self;
}
@end
Run Code Online (Sandbox Code Playgroud) objective-c ×5
ios ×3
singleton ×2
appdelegate ×1
cocoa-touch ×1
concurrency ×1
iphone ×1
sigabrt ×1
static ×1
swift ×1
terminology ×1
variables ×1
xcode ×1