CoreData 中的单例实体
我在标题中使用“单例”一词可能会导致术语不正确。 我现在正在寻找一种好的技术。我有一个名为 user 的实体,它存储用户登录的数据,例如用于发出服务器请求的会话密钥。我只希望这些实体之一永远存在。有这样做的标准技术吗?
到目前为止我所拥有的是这样的
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
}
I might have my terminology incorrect in the title using the word singleton.
I searching for a good technique now. I have an entity named user that stores a users logged in data such as a session key for making server requests. I only ever want one of these entities to exist ever. Is there a standard technique for doing this?
What I have so far is something like this
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我使用 Matt Gallagher 在他的文章 Singletons、AppDelegates 和 top- 中描述的方法级别数据。
它使用宏创建一个“合成单例”类,然后您可以从任何地方访问该类。对于会话、托管对象上下文等非常方便。否则您将不得不到处传递这些内容。
I use Matt Gallagher's approach described in his article Singletons, AppDelegates and top-level data.
It uses a macro to create a "synthesized singleton" class that you can then access from anywhere. Very handy for things like sessions, managed object contexts, etc. Otherwise you'd have to pass these round everywhere.
您的方法应该有效,并且具有灵活性的优点。考虑您的应用程序的未来版本是否能够管理多个帐户;如果您将“单身人士”建模为常规实体,您可以轻松实现这一点。
如果您 100% 确定您永远不会想要这种情况,则可以使用持久存储的
metadata
属性来实现类似的目的。Your approach should work and it has the benefit of being flexible. Consider the possibility that a future version of your app has the ability to manage multiple accounts; you could easily achieve this if you model your "singleton" as a regular entity.
If you're 100% certain that you'd never want that, you could use the persistent store's
metadata
property for things like this.