EXC_BAD_ACCESS using self.performSelector

This is a simple academic not real code.

I want to start the print method using the performSelector function. But if I run this code on the playground, it throws an exception:

EXC_BAD_ACCESS (code = EXC_I386_GPFLT).

the code:

//: Playground - noun: a place where people can play

import UIKit

@objc(Foo)
class Foo: NSObject {

    func timer() {
        self.performSelector( #selector(Foo.print))
    }

    @objc func print() {
        NSLog("print")
    }
}

let instance = Foo()
instance.timer()     // <-- EXC_BAD_ACCESS (code=EXC_I386_GPFLT)

Where is the problem?

+4
source share
2 answers

Try changing Foo.print()to the following:

    @objc func print() -> AnyObject? {
        NSLog("print")
        return nil
    }

I believe the code works on the Playground as well.

performSelectorReturn type not Void.

- make a selection:

func performSelector(_ aSelector: Selector) -> Unmanaged<AnyObject>!

So, Playground is trying to get the value of the result to display. Which is not really coming back.

+3
source

Here is a solution that does not require a change in the function signature:

class Foo {

    func timer() {
        (self as AnyObject).performSelector(#selector(Foo.print))
    }

    @objc func print() {
        NSLog("print")
    }
}

let instance = Foo()
instance.timer()

, Objective-C API-, ...

+3

Source: https://habr.com/ru/post/1648385/


All Articles