Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use perform(#selector(setter:)) to set the value of a property using swift 4?

Tags:

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?

like image 860
Rob C Avatar asked Apr 06 '18 23:04

Rob C


People also ask

How do you use perform in a sentence?

Examples of perform in a SentenceThe doctor had to perform surgery immediately. The magician performed some amazing tricks. The gymnasts performed their routines perfectly.

What do you mean perform?

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.

What type of word is perform?

[transitive, intransitive] perform (something) to entertain an audience by playing a piece of music, acting in a play, etc.

What is the noun of perform?

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.


1 Answers

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))
like image 192
rob mayoff Avatar answered Sep 20 '22 11:09

rob mayoff