我在标题中使用“单例”一词时可能存在术语不正确的情况。 我现在正在寻找一种好的技术。我有一个名为 user 的实体,它存储用户登录的数据,例如用于发出服务器请求的 session key 。我只希望这些实体之一永远存在。有执行此操作的标准技术吗?
到目前为止我所拥有的是这样的
NSManagedObjectContext *moc = [self managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription
entityForName:@"UserEntity" inManagedObjectContext:moc];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
NSArray *array = [moc executeFetchRequest:request error:&error];
if (array == nil)
{
// Deal with error...
}
if ([array count]==0) {
//first run of app
}else if([array count]==1)
{
// id like the code to enter here after every app run except for the first one
}else
{
//dont want this to happen
}
最佳答案
我使用 Matt Gallagher 在他的文章 Singletons, AppDelegates and top-level data 中描述的方法.
它使用宏创建一个“合成单例”类,然后您可以从任何地方访问该类。对于 session 、托管对象上下文等非常方便。否则您必须在各处传递这些内容。
关于iphone - CoreData 中的单例实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5989597/