【问题标题】:[AppDelegate managedObjectContext]: unrecognized selector sent to instance[AppDelegate managedObjectContext]:发送到实例的无法识别的选择器
【发布时间】:2017-07-02 04:22:18
【问题描述】:

我正在学习核心数据存储和检索的教程。下面是我的表格视图代码。

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

@interface DeviceViewController ()
@property(strong) NSMutableArray *devices;

@end

@implementation DeviceViewController

- (NSManagedObjectContext *)managedObjectContext
{
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate performSelector:@selector(managedObjectContext)]) {
        context = [delegate managedObjectContext];
    }
    return context;
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    //Fetch the devices from persistent data store
    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Device"];
    self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];

    [self.tableView reloadData];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

-(NSInteger)numberOfSectionsIntableView: (UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *) tableView numberOfRowsInSection:(NSInteger) section{
    return self.devices.count;
}

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtindexPath:(NSIndexPath *)indexPath{
    static NSString *cellIndentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier forIndexPath:indexPath];

    //Configure the cell
    NSManagedObject *device = [self.devices objectAtIndex:indexPath.row];
    [cell.textLabel setText:[NSString stringWithFormat:@" %@ %@ ",[device valueForKey:@"name"],[device valueForKey:@"version"]]];
    [cell.detailTextLabel setText:[device valueForKey:@"company"]];
    return cell;   
}

我在创建项目时选中了核心数据复选框,但出现以下错误。

    Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[AppDelegate managedObjectContext]: unrecognized selector sent to instance 0x60800003c200'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000107ab8d4b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x00000001070f921e objc_exception_throw + 48
    2   CoreFoundation                      0x0000000107b28f04 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
    3   CoreFoundation                      0x0000000107a3e005 ___forwarding___ + 1013
    4   CoreFoundation                      0x0000000107a3db88 _CF_forwarding_prep_0 + 120
    5   MyStore                             0x0000000106b1ff80 -[DeviceViewController managedObjectContext] + 128
    6   MyStore                             0x0000000106b20058 -[DeviceViewController viewDidAppear:] + 88
    7   UIKit                               0x0000000108084a6c -[UIViewController _setViewAppearState:isAnimating:] + 945
    8   UIKit                               0x00000001080b98d7 -[UINavigationController viewDidAppear:] + 207
    9   UIKit                               0x0000000108084a6c -[UIViewController _setViewAppearState:isAnimating:] + 945
    10  UIKit                               0x00000001080877da __64-[UIViewController viewDidMoveToWindow:shouldAppearOrDisappear:]_block_invoke + 42
    11  UIKit                               0x0000000108085ac4 -[UIViewController _executeAfterAppearanceBlock] + 86
    12  UIKit                               0x0000000107ee977c _runAfterCACommitDeferredBlocks + 653
    13  UIKit                               0x0000000107ed6273 _cleanUpAfterCAFlushAndRunDeferredBlocks + 566
    14  UIKit                               0x0000000107ef9757 __84-[UIApplication _handleApplicationActivationWithScene:transitionContext:completion:]_block_invoke_2 + 194
    15  CoreFoundation                      0x0000000107a5d6ac __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
    16  CoreFoundation                      0x0000000107a426f4 __CFRunLoopDoBlocks + 356
    17  CoreFoundation                      0x0000000107a41e65 __CFRunLoopRun + 901
    18  CoreFoundation                      0x0000000107a41884 CFRunLoopRunSpecific + 420
    19  GraphicsServices                    0x000000010b952a6f GSEventRunModal + 161
    20  UIKit                               0x0000000107edcc68 UIApplicationMain + 159
    21  MyStore                             0x0000000106b2132f main + 111
    22  libdyld.dylib                       0x000000010a9ae68d start + 1
    23  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

我不熟悉在目标 c 中使用 coreData。我已经搜索了完整的堆栈和互联网,但找不到解决方案。

已编辑:我的 AppDelegate.m 如下

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

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    return YES;
}
#pragma mark - Core Data stack

@synthesize persistentContainer = _persistentContainer;

- (NSPersistentContainer *)persistentContainer {
    // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.
    @synchronized (self) {
        if (_persistentContainer == nil) {
            _persistentContainer = [[NSPersistentContainer alloc] initWithName:@"MyStore"];
            [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {
                if (error != nil) {
                    NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }];
        }
    }

    return _persistentContainer;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *context = self.persistentContainer.viewContext;
    NSError *error = nil;
    if ([context hasChanges] && ![context save:&error]) {
        NSLog(@"Unresolved error %@, %@", error, error.userInfo);
        abort();
    }
}

@end

正如我所说,我正在关注这个教程,并且 AppDelegate 类没有任何变化。

【问题讨论】:

  • 信息相当清楚;您的 AppDelegate 类没有函数或属性 managedObjectContext - 您是如何在 AppDelegate 中设置核心数据堆栈的?
  • 您有一个“新”模板应用程序,但可能正在遵循一些较旧的教程。你应该使用appDelegate.persistentContainer.viewContext
  • 能否给出示例代码
  • 字面意思是 delegate.persistentContainer.viewContext 而不是 [delegate managedObjectContext]

标签: ios objective-c core-data


【解决方案1】:

您的代码有两个问题。 1) 您正在使用 performSelector执行该操作)而不是 respondsToSelector(如果允许该操作,则 测试)。 2) appDelete 有一个方法persistentContainer 而不是managedObjectContext

替换

if ([delegate performSelector:@selector(managedObjectContext)]) {
    context = [delegate managedObjectContext];
}

if ([delegate respondsToSelector:@selector(persistentContainer)]) {
    context = delegate.persistentContainer.viewContext;
}

【讨论】:

  • 我的代码有同样的错误..我已经替换了代码,但在第二行 context = delegate.persistentContainer.viewContext;错误是:在“__strong id”类型的对象上找不到属性“persistentContainer”
  • 嘿,乔恩·罗斯,你的解决方案对我不起作用。如果您对同样的问题有任何解决方案,请提供帮助。
猜你喜欢
  • 2021-11-06
  • 1970-01-01
  • 1970-01-01
  • 2019-08-28
  • 2012-07-24
相关资源
最近更新 更多