我终于尝试将我的一个Objective-C应用程序转换为Swift 3.1。我也正在学习Swift教程来帮助我。但是,在尝试转换' for'时,我遇到了以下错误。循环到Swift,在Obj-C中成功运行。我在下面发布了Swift和Objective-C代码,并在Swift中评论了我收到错误的行。我收到了错误
for managedObject: NSManagedObject in myResults{
错误状态
'任何'不能转换为' MSManageObject'
非常感谢任何帮助我指明正确方向的帮助。
//IN SWIFT 3.1
let context: NSManagedObjectContext? =
CoreDataHelper.shared().context
let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
let entity = NSEntityDescription.entity(forEntityName:
"Exhibitors", in: context!)
fetchRequest.entity = entity
var myResults : NSArray = try!
CoreDataHelper.shared().context.fetch(fetchRequest) as NSArray
self.objects = myResults as! [Any]
if !(myResults != nil) || !((myResults.count) != nil) {
print("No Exhibitor objects found to be deleted!")
}
else {
//****Getting error 'Any' is not convertible to 'NSManagedObject'
for managedObject: NSManagedObject in myResults {
if !(managedObject.value(forKey: "fav") == "Yes") {
context?.deleteObject(managedObject)
var error: Error? = nil
// Save the object to persistent store
if !context?.save(error) {
print("Can't Save! \(error) \
(error?.localizedDescription)")
}
print("Exhibitor object deleted!")
}
}
}
//IN OBJECTIVE-C
NSManagedObjectContext *context = [[CoreDataHelper sharedHelper]
context];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]
init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Exhibitors" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *myResults = [[[CoreDataHelper sharedHelper]
context] executeFetchRequest:fetchRequest error:nil];
self.objects = myResults;
if (!myResults || !myResults.count){
NSLog(@"No Exhibitor objects found to be deleted!");
}
else{
for (NSManagedObject *managedObject in myResults) {
if (![[managedObject valueForKey:@"fav"]
isEqualToString:@"Yes"]) {
[context deleteObject:managedObject];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(@"Can't Save! %@ %@", error,
[error localizedDescription]);
}
NSLog(@"Exhibitor object deleted!");
}
}
}
答案 0 :(得分:0)
而不是:
var myResults : NSArray = try! CoreDataHelper.shared().context.fetch(fetchRequest) as NSArray
这样做:
let myResults : [NSManagedObject] = try! CoreDataHelper.shared().context.fetch(fetchRequest)
您还应该使用较少的!
运算符,因为它们可能会导致您的应用崩溃,请尝试使用guard let
模式或?
运算符。
答案 1 :(得分:0)
主要问题是你的注释类型比编译器推断的要差。
不要这样做。除非编译器要求您这样做,否则不要注释类型。
例如,托管对象上下文应该是非可选的
let context = CoreDataHelper.shared().context
您的提取会返回[NSManagedObject]
,永远不会使用NSArray
,也绝不会将不同的类型转换为更加未指定的类型,例如[Any]
简单写一下
let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
let entity = NSEntityDescription.entity(forEntityName: "Exhibitors", in: context)
fetchRequest.entity = entity
do { // its always recommended to do a good error handling !!
self.objects = try CoreDataHelper.shared().context.fetch(fetchRequest)
for managedObject in self.objects {
...
}
} catch { print(error) }
如果objects
为空,则会跳过循环。