ios - 转换为 swift 2.0 在 ManagedObjectContext 中出现错误

标签 ios swift swift2 xcode7

 func read()
 {
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

    let managedContext = appDelegate.managedObjectContext!

    let fetchRequest = NSFetchRequest(entityName: "Coupons")

    var error: NSError?

    let sortDescriptor = NSSortDescriptor(key: "coupon_id", ascending: true)

    // Set the list of sort descriptors in the fetch request,
    // so it includes the sort descriptor

    fetchRequest.sortDescriptors = [sortDescriptor]
    for var i = 0; i < fetch_coupon_category.count ; i++ {

    //condition like here.
    let predicate1 = NSPredicate(format: "coupon_categories == %@", fetch_coupon_category[i])

 // Set the predicate on the fetch request
// Combine the two predicates above in to one compound predicate
//let the predicate on the fetch request

    fetchRequest.predicate = predicate1

我正在尝试将此代码放入 swift2 中,以实现一些 try catch 功能

        do{
            let fetchedResults = try managedObjectContext.executeFetchRequest(fetchRequest)
                as? [NSManagedObject]?

                if let results = fetchedResults {

                for (var i=0; i < results.count; i++) {

                    let single_result = results[i]

                    let out = single_result.valueForKey("coupon_name") as! String
                    tickets.append(single_result)

                }

            }
            else
            {
                print("cannot read")
            }
        }catch let fetchError as NSError{

            print("fetching error: \(fetchError.localizedDescription)")
           // return nil

        }

    }

}

我在管理时遇到错误

'try managedObjectContext' use unresolved identifier

如何将我的代码转换为 swift 2.0,转换我的代码时出现更多错误 -.-

最佳答案

使用try ManagedContext而不是try ManagedObjectContext,因为实际上您将managedObjectContext的值分配给当前 View Controller 中的managedContext

关于ios - 转换为 swift 2.0 在 ManagedObjectContext 中出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32687385/

相关文章:

ios - 如何在 swift 的闭包中抛出错误?

ios - NSURLSession 完成处理程序非常慢

swift - 枚举关联值的问题

xcode - 缺少 iOS Xcode 模板

ios - 将 NSString 转换为 NSAttributedString 无需 alloc init

swift - 如何使用 Xcode 8 IDE 从源代码为 Swift 2.3 构建 RealmSwift?

class - 类初始化中的可选参数

iOS CoreNFC - 类 "NFTechnologyEvent"未加载或不存在

iphone - 带有旋转动画的 CALayer

ios Swift XLForm - 符合协议(protocol) XLFormOptionObject