草庐IT

objective-c - 使 Swift 类可用于 Interface Builder

coder 2023-09-11 原文

<分区>

我有一个 XCode 项目,我是用 Objective-C 开发的,但现在使用 Swift 我有几个类保存为 .swift 文件。当我在 Interface Builder 中将这些作为自定义类引用时,它们不起作用,并且我收到该类不存在的错误消息。

在弥合两者之间的差距方面,我缺少什么?我有使 Objective-C 可用于 Swift 的头文件,但不确定其他方式

谢谢

2014-07-08 20:18:07.463 FoodForTeeth[22030:70b] Unknown class SecondViewController in Interface Builder file.
2014-07-08 20:18:07.496 FoodForTeeth[22030:70b] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIViewController 0x8c85390> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key date.'
*** First throw call stack:
(
    0   CoreFoundation                      0x01acf5e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x018528b6 objc_exception_throw + 44
    2   CoreFoundation                      0x01b5f6a1 -[NSException raise] + 17
    3   Foundation                          0x01513c2e -[NSObject(NSKeyValueCoding) setValue:forUndefinedKey:] + 282
    4   Foundation                          0x0147ff3b _NSSetUsingKeyValueSetter + 88
    5   Foundation                          0x0147f493 -[NSObject(NSKeyValueCoding) setValue:forKey:] + 267
    6   Foundation                          0x014e194a -[NSObject(NSKeyValueCoding) setValue:forKeyPath:] + 412
    7   UIKit                               0x00866cd5 -[UIRuntimeOutletConnection connect] + 106
    8   libobjc.A.dylib                     0x018647d2 -[NSObject performSelector:] + 62
    9   CoreFoundation                      0x01acab6a -[NSArray makeObjectsPerformSelector:] + 314
    10  UIKit                               0x0086582e -[UINib instantiateWithOwner:options:] + 1417
    11  UIKit                               0x006d7c95 -[UIViewController _loadViewFromNibNamed:bundle:] + 280
    12  UIKit                               0x006d843d -[UIViewController loadView] + 302
    13  UIKit                               0x006d873e -[UIViewController loadViewIfRequired] + 78
    14  UIKit                               0x006d8c44 -[UIViewController view] + 35
    15  UIKit                               0x006f2a72 -[UINavigationController _startCustomTransition:] + 778
    16  UIKit                               0x006ff757 -[UINavigationController _startDeferredTransitionIfNeeded:] + 688
    17  UIKit                               0x00700349 -[UINavigationController __viewWillLayoutSubviews] + 57
    18  UIKit                               0x0083939d -[UILayoutContainerView layoutSubviews] + 213
    19  UIKit                               0x0062fdd7 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 355
    20  libobjc.A.dylib                     0x0186481f -[NSObject performSelector:withObject:] + 70
    21  QuartzCore                          0x045ab72a -[CALayer layoutSublayers] + 148
    22  QuartzCore                          0x0459f514 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
    23  QuartzCore                          0x0459f380 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 26
    24  QuartzCore                          0x04507156 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 294
    25  QuartzCore                          0x045084e1 _ZN2CA11Transaction6commitEv + 393
    26  QuartzCore                          0x04508bb4 _ZN2CA11Transaction17observer_callbackEP19__CFRunLoopObservermPv + 92
    27  CoreFoundation                      0x01a9753e __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30
    28  CoreFoundation                      0x01a9748f __CFRunLoopDoObservers + 399
    29  CoreFoundation                      0x01a753b4 __CFRunLoopRun + 1076
    30  CoreFoundation                      0x01a74b33 CFRunLoopRunSpecific + 467
    31  CoreFoundation                      0x01a7494b CFRunLoopRunInMode + 123
    32  GraphicsServices                    0x02ebc9d7 GSEventRunModal + 192
    33  GraphicsServices                    0x02ebc7fe GSEventRun + 104
    34  UIKit                               0x005c594b UIApplicationMain + 1225
    35  FoodForTeeth                        0x0001c42d main + 141
    36  libdyld.dylib                       0x02b5e701 start + 1
    37  ???                                 0x00000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)  

SecondViewController.swift

import UIkit
import CoreData

@objc(SecondViewController) class SecondViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var txtTask: UITextField!
    @IBOutlet var txtDesc: UITextField!
    @IBOutlet var date: UIDatePicker!
    @IBOutlet var dateDisplayLabel: UILabel!


    override func viewDidLoad() {
        super.viewDidLoad()

        configureDatePicker()
    }

    func configureDatePicker() {

        date.addTarget(self, action: "updateDatePickerLabel", forControlEvents: .ValueChanged)

        updateDatePickerLabel()
    }

    func updateDatePickerLabel() {
        dateDisplayLabel.text = dateFormatter.stringFromDate(date.date)
    }

    @lazy var dateFormatter: NSDateFormatter = {
        let dateFormatter = NSDateFormatter()

        dateFormatter.timeStyle = .ShortStyle

        return dateFormatter
        }()


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    //Events
    @IBAction func btnAddTask_Click(sender: UIButton){

        let appDel: foodforteethAppDelegate = UIApplication.sharedApplication().delegate as foodforteethAppDelegate
        let context:NSManagedObjectContext = appDel.managedObjectContext

        let ent = NSEntityDescription.entityForName("Food", inManagedObjectContext: context)

        var newFood = food(entity: ent, insertIntoManagedObjectContext: context)
        newFood.foodname = txtTask.text
        newFood.date = dateFormatter.stringFromDate(date.date)

        context.save(nil)


      /*
        taskMgr.addTask(txtTask.text, desc: dateFormatter.stringFromDate(date.date));

        self.view.endEditing(true)


        txtTask.text = ""
        //txtDesc.text = ""
        //self.tabBarController.selectedIndex = 0;*/

        self.navigationController.popViewControllerAnimated(true)

    }

    //iOS touch functions
    override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!){
        self.view.endEditing(true)
    }


    func textFieldShouldReturn(textField: UITextField!) -> Bool {
        textField.resignFirstResponder();
        return true
    }

}

有关objective-c - 使 Swift 类可用于 Interface Builder的更多相关文章

  1. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  2. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  3. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  4. ruby-on-rails - 如何使辅助方法在 Rails 集成测试中可用? - 2

    我在app/helpers/sessions_helper.rb中有一个帮助程序文件,其中包含一个方法my_preference,它返回当前登录用户的首选项。我想在集成测试中访问该方法。例如,这样我就可以在测试中使用getuser_path(my_preference)。在其他帖子中,我读到这可以通过在测试文件中包含requiresessions_helper来实现,但我仍然收到错误NameError:undefinedlocalvariableormethod'my_preference'.我做错了什么?require'test_helper'require'sessions_hel

  5. objective-c - 在设置 Cocoa Pods 和安装 Ruby 更新时出错 - 2

    我正在尝试为我的iOS应用程序设置cocoapods但是当我执行命令时:sudogemupdate--system我收到错误消息:当前已安装最新版本。中止。当我进入cocoapods的下一步时:sudogeminstallcocoapods我在MacOS10.8.5上遇到错误:ERROR:Errorinstallingcocoapods:cocoapods-trunkrequiresRubyversion>=2.0.0.我在MacOS10.9.4上尝试了同样的操作,但出现错误:ERROR:Couldnotfindavalidgem'cocoapods'(>=0),hereiswhy:U

  6. ruby - 你会如何在 Ruby 中表达成语 "with this object, if it exists, do this"? - 2

    在Ruby(尤其是Rails)中,您经常需要检查某物是否存在,然后对其执行操作,例如:if@objects.any?puts"Wehavetheseobjects:"@objects.each{|o|puts"hello:#{o}"end这是最短的,一切都很好,但是如果你有@objects.some_association.something.hit_database.process而不是@objects呢?我将不得不在if表达式中重复两次,如果我不知道实现细节并且方法调用很昂贵怎么办?显而易见的选择是创建一个变量,然后测试它,然后处理它,但是你必须想出一个变量名(呃),它也会在内存中

  7. ruby - 在 Ruby 中,为什么 Array.new(size, object) 创建一个由对同一对象的多个引用组成的数组? - 2

    如thisanswer中所述,Array.new(size,object)创建一个数组,其中size引用相同的object。hash=Hash.newa=Array.new(2,hash)a[0]['cat']='feline'a#=>[{"cat"=>"feline"},{"cat"=>"feline"}]a[1]['cat']='Felix'a#=>[{"cat"=>"Felix"},{"cat"=>"Felix"}]为什么Ruby会这样做,而不是对object进行dup或clone? 最佳答案 因为那是thedocumenta

  8. ruby-on-rails - self 在 Rails 模型中的值(value)是什么?为什么没有明显的实例方法可用? - 2

    我的rails3.1.6应用程序中有一个自定义访问器方法,它为一个属性分配一个值,即使该值不存在。my_attr属性是一个序列化的哈希,除非为空白,否则应与给定值合并指定了值,在这种情况下,它将当前值设置为空值。(添加了检查以确保值是它们应该的值,但为简洁起见被删除,因为它们不是我的问题的一部分。)我的setter定义为:defmy_attr=(new_val)cur_val=read_attribute(:my_attr)#storecurrentvalue#makesureweareworkingwithahash,andresetvalueifablankvalueisgiven

  9. ruby object.hash - 2

    一个对象的散列值是什么意思?在什么情况下两个对象具有相同的哈希值??还有说Array|Hash不能是Hashkeys,这个跟对象的hash值有关系,为什么? 最佳答案 对于要存储在HashMap或哈希集中的对象,必须满足以下条件:如果认为两个对象相等,则它们的哈希值也必须相等。如果两个对象不被认为是相等的,那么它们的哈希值应该很可能不同(两个不同的对象具有相同哈希值的次数越多,对HashMap/集合的操作性能就越差)。因此,如果两个对象具有相同的哈希值,则很有可能(但不能保证)它们相等。上面“相等”的确切含义取决于散列方法的实现者。

  10. ruby - 为什么 Object 在 Ruby 中既包含内核又继承它? - 2

    在Ruby(1.8.X)中为什么Object既继承了内核又包含了内核?仅仅继承还不够吗?irb(main):006:0>Object.ancestors=>[Object,Kernel]irb(main):005:0>Object.included_modules=>[Kernel]irb(main):011:0>Object.superclass=>nil请注意,在Ruby1.9中情况类似(但更简洁):irb(main):001:0>Object.ancestors=>[Object,Kernel,BasicObject]irb(main):002:0>Object.included

随机推荐