简体   繁体   中英

How to Call same class in class function to instance functionin swift

i have one class in there are 2 methods first is class method and another is normal method and i want to called 2nd method call from class method, i have try many code but still i'm not getting solutions please guide me and help.

class ClassTest : NSObject
{
    class func SentByUserString() -> String
    {
        // i want call here to sample method
        return "hello"
    }

    func  sample() -> Void
    {
        print("Sample Method Called")
    }
}

You need to create static instance of that class and then call that method from that class function using that static instance. Change your code something like this

class ClassTest : NSObject {

    struct Static {
        static var instance: ClassTest?
    }

    class func sharedManager() -> ClassTest {
        if (Static.instance == nil)
        {
            Static.instance = ClassTest()
        }
        return Static.instance!
    }

    class func SentByUserString() -> String {
        // now call here your sample method like this
        Static.instance?.sample()
        return "hello"
    }

    func  sample() -> Void {
        print("Sample Method Called")
    }
}

It's not really something you should be doing, but you can just make an instance of the class in that method, and call the sample method on that instance.

class func SentByUserString() -> String {
        let temp = ClassTest()
        temp.sample()
        return "hello"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM