I'm trying to run this code but it's yielding unexpected results.
class Test: NSObject {
@objc var property: Int = 0
}
var t = Test()
t.perform(#selector(setter: Test.property), with: 100)
print(t.property)
The value being printed is some junk number -5764607523034233277
. How can I set the value of a property using the perform method?
Examples of perform in a SentenceThe doctor had to perform surgery immediately. The magician performed some amazing tricks. The gymnasts performed their routines perfectly.
perform, discharge, execute, transact mean to carry to completion a prescribed course of action. perform is the general word, often applied to ordinary activity as a more formal expression than do, but usually implying regular, methodical, or prolonged application or work: to perform an exacting task.
[transitive, intransitive] perform (something) to entertain an audience by playing a piece of music, acting in a play, etc.
noun. noun. /pərˈfɔrməns/ 1[countable] the act of performing a play, concert, or some other form of entertainment The performance starts at seven.
The performSelector:withObject:
method requires an object argument, so Swift is converting the primitive 100 to an object reference.
The setProperty:
method (which is what #selector(setter: Test.property)
evaluates to) takes a primitive NSInteger
argument. So it is treating the object reference as an integer.
Because of this mismatch, you cannot invoke setProperty:
using performSelector:withObject:
in a meaningful way.
You can, however, use setValue:forKey:
and a #keyPath
instead, because Key-Value Coding knows how to convert objects to primitives:
t.setValue(100, forKey: #keyPath(Test.property))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With