swift - NSObject.setValue(value : AnyObject? , forKey key : String) implemented? )如何

标签 swift nsobject

我这样问是因为我想将该函数单独实现到一个类中。我当然可以从 NSObject 继承,但由于它实际上只是我想要的一种方法,所以我讨厌将所有其他垃圾放入我的对象中。

最佳答案

通过 Command+单击该方法:

Given a value and a key that identifies an attribute, set the value of the attribute. Given an object and a key that identifies a to-one relationship, relate the object to the receiver, unrelating the previously related object if there was one. Given a collection object and a key that identifies a to-many relationship, relate the objects contained in the collection to the receiver, unrelating previously related objects if there were any.

The default implementation of this method does the following:

  1. Searches the class of the receiver for an accessor method whose name matches the pattern -set:. If such a method is found the type of its parameter is checked. If the parameter type is not an object pointer type but the value is nil -setNilValueForKey: is invoked. The default implementation of -setNilValueForKey: raises an NSInvalidArgumentException, but you can override it in your application. Otherwise, if the type of the method's parameter is an object pointer type the method is simply invoked with the value as the argument. If the type of the method's parameter is some other type the inverse of the NSNumber/NSValue conversion done by -valueForKey: is performed before the method is invoked.

  2. Otherwise (no accessor method is found), if the receiver's class' +accessInstanceVariablesDirectly method returns YES, searches the class of the receiver for an instance variable whose name matches the pattern _, _is, , or is, in that order. If such an instance variable is found and its type is an object pointer type the value is retained and the result is set in the instance variable, after the instance variable's old value is first released. If the instance variable's type is some other type its value is set after the same sort of conversion from NSNumber or NSValue as in step 1.

    1. Otherwise (no accessor method or instance variable is found), invokes -setValue:forUndefinedKey:. The default implementation of -setValue:forUndefinedKey: raises an NSUndefinedKeyException, but you can override it in your application.

关于swift - NSObject.setValue(value : AnyObject? , forKey key : String) implemented? )如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36582663/

相关文章:

objective-c - xCode:通过控制台访问对象的属性

Objective-C 设置值 :forKey on c primitive types

ios - 当应用程序处于后台时,位置跟踪会在一段时间后停止

swift - 只画半个圆

swift - 如何快速将 UITableViewCell 数据发送到另一个 ViewController?

ios - 如何使用 SwiftyJson 在 1 NSObject 中初始化 json 中的多个字典

ios - 在两个类之间使用 NSDictionary 值

ios - SwiftyJSON 并添加到现有 [String : AnyObject] dictionary

ios - 如何使用 MDCTabBar

objective-c - 将上下文添加到 UI 控件或 NSObject