嘿,obj-c中的原始苹果指南就在这里,
例3.2
我一直在完成指南,无法让程序运行,我收到了这些错误:
'AnyObject?' does not have a member named 'identifier'
line: result.identifier = "HelloWorld"
和
error: cannot convert the expression's type 'AnyObject?' to type '()'
Line: return result
我做错了什么?
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn, row: Int){
var names: [String] = ["Anna","Alex","brain","jack","gg"]
var result: AnyObject? = tableView.makeViewWithIdentifier("HelloWorld", owner: self)
if result == nil
{
// Create the new NSTextField with a frame of the {0,0} with the width
// of the table.
result = NSTextField(frame: NSRect())
// set identifier of the NSTextField instance to HelloWorld.
result.identifier = "HelloWorld"
}
result = names[row]
return result
}
新工作代码
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn, row: Int) -> NSTextField{
var names = ["Anna","Alex","Brain","Jack","Hello"]
var result: NSTextField? = tableView.makeViewWithIdentifier("HelloWorld", owner: self) as? NSTextField
if result == nil
{
// Create the new NSTextField with a frame of the {0,0} with the width
// of the table.
result = NSTextField(frame: NSRect())
// set identifier of the NSTextField instance to HelloWorld.
result?.identifier = "HelloWorld"
}
result!.bezeled = false
result?.stringValue = names[row]
return result!
}
答案 0 :(得分:1)
这里:
var result: AnyObject? = tableView.makeViewWithIdentifier("HelloWorld", owner: self)
您已将result
变量声明为可选的AnyObject - 并且此协议没有identifier
属性,而是NSTextField
的属性。
您应该做的是使用正确的类型声明该变量:
var result: NSTextField? = tableView.makeViewWithIdentifier("HelloWorld", owner: self) as? NSTextField
由于类型推断也可以缩短:
var result = tableView.makeViewWithIdentifier("HelloWorld", owner: self) as? NSTextField
旁注:我认为你的if
正在检查相反的情况:
if result != nil
虽然我认为它应该是:
if result == nil
旁注2
您的函数中没有声明返回值,但您返回NSTextField
的实例。
您应该将签名更改为:
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn, row: Int) -> NSView
并将return语句更改为:
return result!
请注意,result
被定义为可选,但是查看方法实现,最后一个非零值可用,所以我使用了强制解包并声明该方法返回非 - 价值。如果你愿意,当然可以随意改变它。