【发布时间】:2017-01-25 14:34:10
【问题描述】:
我已经看到了关键字Use of 'self' in property 的所有问题
但仍然无法解决。我刚开始学习 swift 3.01,我的 Xcode 版本是 8.2。请帮帮我!
我正在更改the app Apple provided。
我想创建一个textView,以便用户可以键入文本并存储它。
当我更改Meal.swift 时,出现错误:
Error :Use of 'self' in property access 'content' before self.init initializes self 就在代码的最后:
import UIKit
import os.log
class Meal: NSObject, NSCoding {
//MARK: Properties
var name: String
var photo: UIImage?
var content: String
//MARK: Archiving Paths
static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
static let ArchiveURL = DocumentsDirectory.appendingPathComponent("meals")
//MARK: Types
struct PropertyKey {
static let name = "name"
static let photo = "photo"
static let content = "content"
}
//MARK: Initialization
init?(name: String, photo: UIImage?, content: String) {
// The name must not be empty
guard !name.isEmpty else {
return nil
}
// The content must not be empty
guard !content.isEmpty else {
return nil
}
// Initialize stored properties.
self.name = name
self.photo = photo
self.content = content
}
//MARK: NSCoding
func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: PropertyKey.name)
aCoder.encode(photo, forKey: PropertyKey.photo)
aCoder.encode(content, forKey: PropertyKey.content)
}
required convenience init?(coder aDecoder: NSCoder) {
// The name is required. If we cannot decode a name string, the initializer should fail.
guard let name = aDecoder.decodeObject(forKey: PropertyKey.name) as? String else {
os_log("Unable to decode the name for a Meal object.", log: OSLog.default, type: .debug)
return nil
}
// Because photo is an optional property of Meal, just use conditional cast.
let photo = aDecoder.decodeObject(forKey: PropertyKey.photo) as? UIImage
// Must call designated initializer.
self.init(name: name, photo: photo, content: content)// Error happened to here by this : Error :Use of 'self' in property access 'content' before self.init initializes self
}
}
请帮我找出问题所在,最好的祝福!
【问题讨论】:
-
至少有一个问题是你的
init?(coder aDecoder: NSCoder)引用content而没有初始化它。你的意思是有一个本地值传递给指定的init,因为编译器认为你指的是self.content... -
感谢您的回复,改正我在英语语法上的错误。我大概知道。