iphone - CoreData 中的单例实体

标签 iphone cocoa-touch core-data

我在标题中使用“单例”一词时可能存在术语不正确的情况。 我现在正在寻找一种好的技术。我有一个名为 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/

相关文章:

iOS:JavaScript 无法在 WKWebView 上运行

objective-c - 将方法的所有参数传递到 NSLog

ios - CoreData NSPredicate date() 函数

iphone - 您将如何最小化或压缩 Core Data sqlite 文件大小?

ios - 保存时随机核心数据 EXC_BAD_ACCESS

iphone - 我应该如何保护 iOS 中的 SQLite 数据库?

ios - 通过 iPhone IOS 测试 React Native

iphone - iPhone中的MDM集成文档

iphone - 如何 - 在 iPhone 上恢复应用程序数据库的位置

iphone - 带列的 UITableView