简体   繁体   中英

Undeclared identifier error when adding Core Data to existing Xcode project

I have an existing project and I want to use CoreData.

Upon creation of the project, the CoreData.framework is already added under my Frameworks group, and it is under Link Binary With Libraries in my project's Target -> Build Phases. I didn't check "Use Core Data" when I created this project-- the check box was not even there --it was just simply in my project. I use Xcode version 4.6.3.

Reading the tutorials, I went to my App-Prefix.pch and added an import to CoreData. It now looks like this:

#import <Availability.h>

#ifndef __IPHONE_5_0
#warning "This project uses features only available in iOS SDK 5.0 and later."
#endif

#ifdef __OBJC__
    #import <UIKit/UIKit.h>
    #import <CoreData/CoreData.h>
    #import <Foundation/Foundation.h>
#endif

Then, I added the following in my AppDelegate.h :

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

- (void)saveContext;

And now, when I override the getter for managedObjectContext , Xcode throws an error:

Use of undeclared identifier '_managedObjectContext'; did you mean 'NSManagedObjectContext'?

This is my getter method in AppDelegate.m :

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

    NSPersistentStoreCoordinator* psc = [self persistentStoreCoordinator];

    if(psc != nil)
    {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:psc];
    }

    return _managedObjectContext;
}

I also tried putting the .pch file in my Copy Bundle Resources but to no avail. Help?

You've set everything up correctly (note that you don't need to add the PCH to the Copy Bundle Resources build phase). The reason you're getting that error is because the _managedObjectContext ivar is not getting synthesized, because you're overriding the getter on a read-only property. You either need to change the property to be readwrite (which I wouldn't recommend), redefine the property as readwrite in a class extension, or define the ivar manually in a class extension or the implementation block.

For readonly properties you Even implement there is no Ivar created by the compiler. Declare the Variable

NsmanagedObjectContext *_managedObjectContext;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM