核心数据,无法检索/设置我的属性。最常见的错误?

时间:2012-08-07 16:28:42

标签: iphone ios5 core-data uiviewcontroller

SUBJECT:核心数据,无法从VC中检索/设置我的属性。最常见的错误?

通过这个网站搜索但无法得到我需要的答案(虽然很多好的提示),所以我想发布这个问题希望它能解决我的问题我已经有了几个星期了!是的,非常令人沮丧,你可能知道这种感觉!所以任何帮助都会很棒 - 谢谢! : - )

大略介绍:

iOS 5.1项目。获得核心数据(在main.h / NSLog中测试),但我无法从其他视图控制器检索和设置实体属性(数据)。 Xcode从其他视图控制器中识别出AppDelegate中的singelton“AppContent”,但不识别实体名称及其属性。

最常见的错误是什么?

我觉得我错过了在正确的地方导入某些文件等等......

更多细节;

仅供参考:我正在尝试使用Matt Campell推荐的方法,该方法在AppDelegate中创建一个单例,可以在整个应用程序中使用从任何视图控制器使用managedObjectContext,并检索并保存数据到Core Data及其实体及其各自的属性。这是通过将以下两个文件导入应用程序来完成的;

appContent.h

#import <Foundation/Foundation.h>
#import "Contest.h"  // Root Entity in CD model
#import "Player.h"

@interface AppContent : NSObject

+(AppContent *)sharedContent;

@property(strong, readonly) id rootObject;

-(void)save;
-(void)rollback;

@end

appContent.m

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

@interface AppContent()

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

@end

@implementation AppContent
NSManagedObjectModel *_managedObjectModel;
NSPersistentStoreCoordinator *_persistentStoreCoordinator;
NSManagedObjectContext *_managedObjectContext;
id _rootObject;

static AppContent *singletonInstance = nil;

+ (AppContent *)sharedContent{
    @synchronized(self){
        if (singletonInstance == nil)
            singletonInstance = [[self alloc] init];

        return(singletonInstance);
    }
}


- (NSURL *)dataStoreURL {

    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

    return [NSURL fileURLWithPath:[docDir stringByAppendingPathComponent:@"DataStore.sql"]];
}

- (NSManagedObjectModel *)managedObjectModel {
    if (_managedObjectModel) {
        return _managedObjectModel;
    }
    _managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];    
    return _managedObjectModel;
}

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

    NSError *error = nil;
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
                                               configuration:nil
                                                         URL:[self dataStoreURL]
                                                     options:nil
                                                       error:&error]) {
        NSLog(@"Unresolved Core Data error with persistentStoreCoordinator: %@, %@", error, [error userInfo]);
    }    

    return _persistentStoreCoordinator;
}

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

    if ([self persistentStoreCoordinator]) {
        _managedObjectContext = [[NSManagedObjectContext alloc] init];
        [_managedObjectContext setPersistentStoreCoordinator:[self persistentStoreCoordinator]];
    }

    return _managedObjectContext;
}

-(id)rootObject{
    if(_rootObject)
        return _rootObject;

// #warning Replace [CHANGE] with your root object entity name
    NSString *entityName = @"Contest";
    NSManagedObjectContext *context = [self managedObjectContext];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:entityName
                                          inManagedObjectContext:context];
    request.entity = entity;
    NSArray *listOfObjects = [context executeFetchRequest:request
                                                error:nil];
    if([listOfObjects count] == 1){
        _rootObject = [listOfObjects lastObject];
        return _rootObject;
    }
    _rootObject = [NSEntityDescription insertNewObjectForEntityForName:entityName
                                            inManagedObjectContext:context];

    // Adding some testdata (only first time...)
    // Contest
    Contest *c = _rootObject;
    c.name = @"Big Game 1";

    // Players
    Player *p1 = (Player *) [NSEntityDescription insertNewObjectForEntityForName:@"Player"
                                                          inManagedObjectContext:context];
    p1.name = @"Player One";
    [c addPlayersObject:p1];

    Player *p2 = (Player *) [NSEntityDescription insertNewObjectForEntityForName:@"Player"
                                                              inManagedObjectContext:context];
    p2.name = @"Player Two";
    [c addPlayersObject:p2];

    [self save];

    return _rootObject;
}

-(void)save{
    NSError *error = nil;
    NSManagedObjectContext *context = [self managedObjectContext];
    if([context hasChanges])
        [context save:&error];
    if(error)
        NSLog(@"Warning: Error saving to data store.  %@", error);
}

-(void)rollback{
    NSManagedObjectContext *context = [self managedObjectContext];
    if([context hasChanges])
        [context rollback];
}

@end

以下是模型文件(由CD模型编辑器创建);

Contest.h

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

@class Player;

@interface Contest : NSManagedObject

@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSSet *players;
@end

@interface Contest (CoreDataGeneratedAccessors)

- (void)addPlayersObject:(Player *)value;
- (void)removePlayersObject:(Player *)value;
- (void)addPlayers:(NSSet *)values;
- (void)removePlayers:(NSSet *)values;

@end

Contest.m

#import "Contest.h"
#import "Player.h"

@implementation Contest

@dynamic name;
@dynamic players;

@end

Player.h

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

@class Contest;

@interface Player : NSManagedObject

@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) Contest *contests;

@end

Player.m

#import "Player.h"
#import "Contest.h"


@implementation Player

@dynamic name;
@dynamic contests;

@end

这是一个视图控制器

尝试在此处获取核心数据实体及其属性,但Xcode看到的是appContent,但无法识别它,在构建时会出现错误“无法找到属性播放器”......

contestPlayerVC.h

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


@interface contestPlayerVC : UIViewController

@property (strong, nonatomic) IBOutlet UITextField *playerNameField;
@property (strong, nonatomic) IBOutlet UITextField *playerMailField;
@property (strong, nonatomic) IBOutlet UIButton *playerSaveButton;

@property (weak, nonatomic) AppContent *content;

// Test
// @property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;


- (IBAction)playerChooseImage:(UIButton *)sender;

- (IBAction)dismissModal:(UIButton *)sender;

- (IBAction)hideKeyboard:(id)sender;

- (IBAction)playerSave:(UIButton *)sender;

@end

contestPlayerVC.m 由于问题出在方法viewDidLoad ...

中,因此未显示孔文件
#import "contestPlayerVC.h"

@interface contestPlayerVC ()

@end

@implementation contestPlayerVC
@synthesize playerNameField, playerMailField, playerSaveButton, content;

- (void)viewDidLoad {

    [super viewDidLoad];
    // Do any additional setup after loading the view.

    // Call 1 - seems to work ok
    self.content = [AppContent sharedContent];

////// Call 2 - gives error, can't find property "player" - WHY?
    // Trying to set textfield to CD Entity "Player" and it's property "name"
    self.playerNameField.text = self.content.player.name;

    NSLog(@"Player is: %@", self.content.player.name);

    // Call 3 - works ok
    NSLog(@"Content is: %@", self.content.description);

}
...

有任何提示或建议吗?谢谢! : - )

顺便说一下:对于长篇文章感到抱歉,我不确定其他人如何能够很好地描述我的问题,让任何人都能理解它。如果你全部阅读 - 我印象深刻,如果你帮助我解决这个问题,我将非常高兴。可能是我完全错过了一些基本的东西。谢谢;-)

2 个答案:

答案 0 :(得分:2)

您的错误,无法在player上找到self.content属性,是因为您的AppContent类未声明该名称的任何属性。让我们一次一行地查看您的代码:

self.content = [AppContent sharedContent];

现在self.content是AppContent类型的对象,因此将来对self.content.something的任何调用都将查找在该类上声明的可见方法或属性(通常在“AppContent.h”中)。

self.playerNameField.text = self.content.player.name;

我们在这里寻找AppContent对象中名为player的属性,该对象具有标题:

#import <Foundation/Foundation.h>
#import "Contest.h"  // Root Entity in CD model
#import "Player.h"

@interface AppContent : NSObject

+(AppContent *)sharedContent;

@property(strong, readonly) id rootObject;

-(void)save;
-(void)rollback;

@end

有一个名为@property的{​​{1}} - 你有一个player属性,你导入了“Player.h”标题,但你永远不会声明属性你是试图访问。您需要添加如下行:

rootObject

并在{AppContent.m“文件中@property(strong) Player * player; 或者提供适当的访问者方法来支持该属性。

答案 1 :(得分:2)

@ user1578933好的,让我们备份一下并考虑每件作品的责任:

  • 比赛是负责与比赛相关的所有事情的根(第一)对象,包括名称和球员名单
  • 播放器负责播放器的所有内容,包括播放器名称
  • AppContent 负责管理对象图(检索对象图,以便您可以使用它并记住用户添加和删除的内容)
  • contestPlayerVC 负责展示内容(来自AppContent)

在您的应用中,所有内容都以比赛开头。在 AppContent 实现中,您拥有生成该属性 rootObject 的代码,这是第一次创建竞赛对象的位置。

注意您已将其定义为 id ,因为您正在为我们的程序直接复制此代码,但您也可以将 rootObject 定义为像这样输入比赛

-(Contest *) rootObject;

这是您的对象图的输入点。我们的想法是,您将访问 AppContent (使用Singleton模式),然后检索比赛对象。 比赛对象将包含 NSSet 对象集合,其中包含对集合中每个玩家的引用。

以下是如何在视图控制器中使用它的示例:

- (void)viewDidLoad {
    [super viewDidLoad];

    self.content = [AppContent sharedContent];

    //get reference to the root object contest
    Contest *theContest = (Contest *)self.content.rootObject;

    //get an array based reference to the players in theContest
    NSArray *players = [theContest.players allObjects];

    //Example of getting a reference to an individual player:
    Player *p1 = [players objectAtIndex:0];

}

这实际上是您将此内容添加到视图控制器的方式;对于表视图控制器,您可以使用索引路径行属性来查找哪个播放器在哪个表视图单元格中运行(请参阅cellForRowAtIndexPath)。

@ user1578933 - 在阅读了这篇文章以及你在Mobile App Mastery Institute上留下的内容之后,您似乎错过了对对象图的理解以及所有这些对象关系的组织方式。我最近添加了一些关于如何使用和考虑Objective-C object graph here的其他内容。另外,我会仔细查看有关Objective-C,Table Views和Core Data的部分。