2014-07-07 3 views
18

스위프트에서 managedObjectContext: NSManagedObjectContext이라는 계산 된 속성이 있습니다. 내가 초기화 할 때이 같은 :스위프트 : 자체에서 ""에 할당 할 수 없습니다

var managedObjectContext: NSManagedObjectContext? { 
    get { 
     createManagedObjectContext() 
     return self.managedObjectContext 
    } 
    set(newManagedObjectContext) { 
     self.manageObjectContext = newManagedObjectContext 
    } 
} 

func createManagedObjectContext() -> NSManagedObjectContext { 

    if let coordinator = persistentStorageCoordinator() as NSPersistentStoreCoordinator! 
    { 
     self.managedObjectContext = NSManagedObjectContext() 
     self.managedObjectContext!.persistentStoreCoordinator = coordinator 

     NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleBackgroundMOCDidSaveNotification:", name: NSManagedObjectContextDidSaveNotification, object: self.managedObjectContext) 
    } 

    return self.managedObjectContext!; 
} 

을 내가 말하는 오류가 점점 오전 : Cannot assign to "managedObjectContext" in self합니다.

누구든지 해결할 수 있습니까?

미리 감사드립니다.

+1

구조체 또는 클래스를 생성 하시겠습니까? –

+0

클래스입니다. – keshav

+1

나머지 수업을 보여 주시겠습니까? 도움이 될 것입니다. –

답변

1

문제는 계산 된 속성을 표준 속성으로 사용하는 것이므로 실제로 setter를 재귀 적으로 호출하려고 시도하는 것입니다. 예를 들어, "센터"속성을 에 -

var managedObjectContext: NSManagedObjectContext? 

전산화 속성 값이 다른 속성에 따라 필요할 때 계산되는 것이다 - 당신은 여기에 계산 된 속성을 사용하는 단지 표준 등록이 필요하지 않습니다 스위프트 프로그래밍 언어 -

var center: Point { 
    get { 
     let centerX = origin.x + (size.width/2) 
     let centerY = origin.y + (size.height/2) 
     return Point(x: centerX, y: centerY) 
    } 
    set(newCenter) { 
     origin.x = newCenter.x - (size.width/2) 
     origin.y = newCenter.y - (size.height/2) 
    } 
} 

발췌에서 : Apple Inc.의 "스위프트 프로그래밍 언어."아이북. https://itunes.apple.com/au/book/swift-programming-language/id881256329?mt=11

센터는 기원과 크기에 의해 결정된다 중심을 설정하면 원점

8

에게 게으른 저장 특성에 영향을 미치는 (스위프트 프로그래밍 언어 책을 참조 페이지 313) 당신이 뭘 하려는지에 대한 더 적합 이리. 당신이 재산을 처음으로 (그리고 첫 번째 시간)에 액세스를 시도 할 때까지

lazy var managedObjectContext = createManagedObjectContext() 

createManagedObjectContext()가 호출되지 않습니다.

1

추가하십시오! =)

// MARK: - Core Data stack 

lazy var applicationDocumentsDirectory: NSURL = { 
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.YOURNAME_OTHERS.YOURAPP" in the application's documents Application Support directory. 
    let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) 
    return urls[urls.count-1] as NSURL 
}() 

lazy var managedObjectModel: NSManagedObjectModel = { 
    // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. 
    let modelURL = NSBundle.mainBundle().URLForResource("YOURAPP", withExtension: "momd") 
    return NSManagedObjectModel(contentsOfURL: modelURL) 
}() 

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { 
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. 
    // Create the coordinator and store 
    var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) 
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("YOURAPP.sqlite") 
    var error: NSError? = nil 
    var failureReason = "There was an error creating or loading the application's saved data." 
    if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { 
     coordinator = nil 
     // Report any error we got. 
     let dict = NSMutableDictionary() 
     dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" 
     dict[NSLocalizedFailureReasonErrorKey] = failureReason 
     dict[NSUnderlyingErrorKey] = error 
     error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) 
     // Replace this with code to handle the error appropriately. 
     // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
     NSLog("Unresolved error \(error), \(error!.userInfo)") 
     abort() 
    } 

    return coordinator 
}() 

lazy var managedObjectContext: NSManagedObjectContext? = { 
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. 
    let coordinator = self.persistentStoreCoordinator 
    if coordinator == nil { 
     return nil 
    } 
    var managedObjectContext = NSManagedObjectContext() 
    managedObjectContext.persistentStoreCoordinator = coordinator 
    return managedObjectContext 
}() 

// MARK: - Core Data Saving support 

func saveContext() { 
    if let moc = self.managedObjectContext { 
     var error: NSError? = nil 
     if moc.hasChanges && !moc.save(&error) { 
      // Replace this implementation with code to handle the error appropriately. 
      // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
      NSLog("Unresolved error \(error), \(error!.userInfo)") 
      //abort() 
     } 
    } 
} 
37

let 상수에 값을 할당하려고 할 때도이 컴파일 오류가 발생합니다. 변수의 유형을 var으로 변경하면 해결됩니다 (이 경우).

관련 문제