未识别的选择器mutableCopyWithZone

3
我正在跟随这个站点上的Core Data教程进行学习。http://www.appcoda.com/introduction-to-core-data/,但是我遇到了以下错误: 2016-06-23 17:55:11.905 MyStore[6020:596233] -[NSAsynchronousFetchResult mutableCopyWithZone :]: unrecognized selector sent to instance 0x7f8950e12eb0 我设置了断点,似乎错误来自于以下程序。
- (void) viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    
    //Fetch the devices from the persistent store.
    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Device"];
    self.devices = [[managedObjectContext executeRequest:fetchRequest error:nil] mutableCopy]; //error here
    
    [self.tableView reloadData];
}

我有一个声明为NSMutableArray的“devices”属性。
任何形式的帮助都会受到赞赏。

1
你的executeRequest:error:调用结果是一个NSAsynchronousFetchResult实例。这可能是因为你在使用NSFetchRequest而不是NSAsynchronousFetchRequest时发生了这种情况,但是在你发布的代码中并非如此。你可以在这里阅读更多关于异步获取的内容 - https://www.bignerdranch.com/blog/new-in-core-data-and-iOS-8-asynchronous-fetching/ - Borys Verebskyi
谢谢Boris,我已经意识到了 :) 看看我的回答哈哈 - user5412293
2个回答

4

我在按照流程操作时使用了错误的方法。

我应该使用的方法是executeFetchRequest,而我错误地使用了executeRequest。前者确实返回一个NSArray,而后者返回一个NSPersistentStoreResult。

以下是这两种方法:

- (nullable NSArray *)executeFetchRequest:(NSFetchRequest *)request error:(NSError **)error;
- (nullable __kindof NSPersistentStoreResult *)executeRequest:(NSPersistentStoreRequest*)request error:(NSError **)error NS_AVAILABLE(10_10, 8_0);

感谢Volodymyr的帮助,我能够检查我的返回对象确实不是我所期望的类型,并且从那里我可以改变方法,但后来我发现返回的对象更加复杂,并且有一个可以使用的NSArray属性。
以下是我的代码及测试 :)
- (void) viewDidAppear:(BOOL)animated {

    [super viewDidAppear:animated];

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

    id whatAreYou = [managedObjectContext executeRequest:fetchRequest error:nil];
    NSLog(@"%@", [whatAreYou class]); // turns out you are a NSPersistentStoreResult
    // lucky for me you are have finalResult property that returns an NSArray. :)

    self.devices = [[whatAreYou finalResult] mutableCopy]; //no more errors here :)

    [self.tableView reloadData];
}

非常感谢您的帮助。检查对象类型是我从现在开始要添加到我的调试工具中的内容 :)

3
mutableCopy 中,包含了 mutableCopyWithZone。这意味着从您的获取请求返回的对象没有实现 mutableCopyWithZone 方法。您可以尝试使用 copy 方法代替。但是仍然需要检查返回的对象并确定其是否实现了 mutableCopyWithZonecopyWithZone 方法。

谢谢您的回复。我尝试了复制,但它没有起作用。根据此代码 - (nullable NSArray *)executeFetchRequest:(NSFetchRequest *)request error:(NSError **)error; 返回的对象是NSArray。 - user5412293
1
你能把这最后一行拆分成两个动作吗?第一个动作获取对象,第二个动作执行复制。获取对象后,检查它的类以确保它是你想要的类型,并检查它是否为空。你知道如何执行此类检查吗? - Volodymyr
非常感谢您的回复和帮助。我按照您说的做了,但是返回了一个不同的对象 :) 请查看我的答案以获取完整细节。 - user5412293

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接