+ entityForName:nil不是合法的NSManagedObjectContext参数,用于搜索实体名称“Account”

时间:2013-12-09 13:59:29

标签: ios core-data login xcode5 keychain

我尝试了很多选项,但无法找到解决此问题的方法。我创建了一个Core Data文件并命名了实体Account,创建了一个名为username的字符串属性。然后将实体的类编辑为NSManagedObject,不确定这是否正确。现在,以下代码在我的LoginViewController中:

- (void)viewDidLoad
{
    [super viewDidLoad];

    ITAppDelegate *appDelegate = (ITAppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = appDelegate.managedObjectContext;

    Account *newAccount = [NSEntityDescription insertNewObjectForEntityForName:@"Account" inManagedObjectContext:context];
    [newAccount setValue:@"Jorge" forKey:@"username"];
    [newAccount setPassword:@"password"];

    NSLog(@"username:%@   password: %@", [newAccount username], [newAccount password]);

}

我关注了This Tutorial,我的代码文件如下所示:

ITAppDelegate.h

#import <UIKit/UIKit.h>

@interface ITAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

@end

ITAppDelegate.m

#import "ITAppDelegate.h"
#import "LoginViewController.h"

@implementation ITAppDelegate

@synthesize managedObjectContext = _managedObjectContext;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
@synthesize managedObjectModel = _managedObjectModel;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary    *)launchOptions
{
    // Override point for customization after application launch.
    return YES;
}

#pragma mark - Core Data stack

- (NSManagedObjectContext *)managedObjectContext
{
if (_managedObjectContext != nil)
{
    return _managedObjectContext;
}

NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil)
{
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext  setPersistentStoreCoordinator:coordinator];
}
return _managedObjectContext;
}


- (NSManagedObjectModel *)managedObjectModel
{
if (_managedObjectModel != nil)
{
    return _managedObjectModel;
}
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Model" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return _managedObjectModel;
}


- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (_persistentStoreCoordinator != nil)
{
    return _persistentStoreCoordinator;
}

    return _persistentStoreCoordinator;
}

@end

AccountBase.h

#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>

@interface AccountBase : NSManagedObject

@property (nonatomic, retain) NSString *username;


@end

AccountBase.m

#import "AccountBase.h"

@implementation AccountBase

@dynamic username;

@end

Account.h

#import "AccountBase.h"
#import <CoreData/CoreData.h>

@interface Account : AccountBase

@property (nonatomic, assign) NSString *password;

@end

Account.m

#import "Account.h"
#import "KeychainHelper.h"

@implementation Account

- (NSString*)password
{
    if (self.username)
        return [KeychainHelper getPasswordForKey:self.username];
    return nil;
}

- (void)setPassword:(NSString*)aPassword
{
    if (self.username)
        [KeychainHelper setPassword:aPassword forKey:self.username];
}

- (void)prepareForDeletion
{
    if (self.username)
        [KeychainHelper removePasswordForKey:self.username];
}
@end

KeychainHelper.h

#import <Foundation/Foundation.h>

@interface KeychainHelper : NSObject

+ (NSString*)getPasswordForKey:(NSString*)aKey;
+ (void)setPassword:(NSString*)aPassword forKey:(NSString*)aKey;
+ (void)removePasswordForKey:(NSString*)aKey;

@end

KeychainHelper.m

#import "KeychainHelper.h"
#import <Security/Security.h>

@interface KeychainHelper ()
+ (NSMutableDictionary*)dictionaryForKey:(NSString*)aKey;
@end

@implementation KeychainHelper


static const NSString *ironTrainers = @"com.domain.myapplication";

+ (NSMutableDictionary*)dictionaryForKey:(NSString*)aKey
{
    NSData *encodedKey = [aKey dataUsingEncoding:NSUTF8StringEncoding];

    NSMutableDictionary *searchDictionary = [NSMutableDictionary dictionary];

    [searchDictionary setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
    [searchDictionary setObject:encodedKey forKey:(__bridge id)kSecAttrGeneric];
    [searchDictionary setObject:encodedKey forKey:(__bridge id)kSecAttrAccount];
    [searchDictionary setObject:ironTrainers forKey:(__bridge id)kSecAttrService];

    return searchDictionary;
}  

+ (NSString*)getPasswordForKey:(NSString*)aKey
{
    NSString *password = nil;

    NSMutableDictionary *searchDictionary = [self dictionaryForKey:aKey];
    [searchDictionary setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
    [searchDictionary setObject:(id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];

    CFTypeRef result = NULL;
    BOOL statusCode = SecItemCopyMatching((__bridge CFDictionaryRef)searchDictionary, &result);
    if (statusCode == errSecSuccess) {
        NSData *resultData = CFBridgingRelease(result);
        password = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
    }
    return (__bridge NSString *)(result);
}

+ (void)removePasswordForKey:(NSString*)aKey
{
    NSMutableDictionary *keyDictionary = [self dictionaryForKey:aKey];
    SecItemDelete((__bridge CFDictionaryRef)keyDictionary);
 }

+ (void)setPassword:(NSString*)aPassword forKey:(NSString*)aKey
{
    [KeychainHelper removePasswordForKey:aKey];

    NSData *encodedPassword = [aPassword dataUsingEncoding:NSUTF8StringEncoding];

    NSMutableDictionary *keyDictionary = [self dictionaryForKey:aKey];
    [keyDictionary setObject:encodedPassword forKey:(__bridge id)kSecValueData];
    SecItemAdd((__bridge CFDictionaryRef)keyDictionary, nil);
}

@end

任何帮助表示赞赏。感谢。

5 个答案:

答案 0 :(得分:37)

- (NSManagedObjectContext *)managedObjectContext
{
    if (managedObjectContext != nil) return managedObjectContext;

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {

        managedObjectContext = [[NSManagedObjectContext alloc] init];
        [managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return managedObjectContext;
}
  • 您尚未提供persistentStoreCoordinator
  • 的延迟加载实现
  • 因此coordinator始终为nil
  • 因此您将始终从此方法返回nil
  • 表示您将始终收到上述错误。

解释错误:

  

+ entityForName:nil不是合法的NSManagedObjectContext参数,用于搜索实体名称“帐户”

通过阅读它并不是很明显,但这意味着nil不是传递托管对象上下文的合法内容。在第一次阅读时,看起来你正在做entityForName:nil但事实并非如此。

要解决此问题,您需要提供有效的持久性存储协调器。我有一篇小文章here,它解释了设置核心数据堆栈所需的代码很少,这可能会对您有所帮助。

答案 1 :(得分:0)

就我而言,我使用具有不同并发类型的多个上下文(父/子)来提高性能。我有三种情况:

  1. storeContext这是唯一已设置persistentStoreCoordinator的上下文。
  2. viewContext,其父级为storeContext
  3. backgroundContext其父应该是viewContext 我忘了设置backgroundContext.parent = viewContext
  4. backgroundContext上保存实体会产生相同的错误......

      

    + entityForName:nil不是搜索实体名称的合法NSManagedObjectContext参数...

    ...因为backgroundContext不是父/子上下文链的一部分。

    backgroundContext&#39; s parent设置为viewContext,将链建立回持久存储协调员并解决错误。

答案 2 :(得分:0)

我遇到了这个entityForName: nil错误,但它最终变成了一个红色的鲱鱼,只有在我的CI上运行单元测试时才表现出来。在测试期间,应用程序遇到了由NSAttributedString's HTML Importer引起的一些奇怪的线程条件。正在从HTML创建NSAttributedString时,正在发生主队列与Core Data交互的异步调度。

只是在这里发布我的经验,以防它最终帮助别人。 :)

答案 3 :(得分:0)

从Core Data获取数据时遇到了相同的错误。原因是未正确设置上下文对象的值,并且在获取结果后对其进行了设置。因此,在遇到提取请求之前正确设置上下文可以完成工作。

答案 4 :(得分:-1)

可能由于实体名称及其类名称不匹配而发生。确保您的Account实体在.xcdatamodeld文件中具有适当的类名。