Thijs
Thijs

Reputation: 717

How to access an Objective-C class method from an instance in Swift

If there is Objective-C code like this:

@protocol MyProtocol
@required
+ (void)aClassMethod;
- (void)anInstanceMethod;
@end

@interface MyClass <MyProtocol>
@end

@implementation MyClass
+(void)aClassMethod {
}
-(void)anInstanceMethod {
}
@end

And have only the following available in Swift:

func myFunc(obj: MyProtocol) {
  // want to access aClassMethod here
}

Then how can I access aClassMethod on obj?

--edit--

Some clarification on what I'm trying to achieve. Let's throw in another class:

@interface AnotherClass <MyProtocol>
@end

@implementation AnotherClass
+(void)aClassMethod {
    // Here I'm doing something different than in MyClass
}
-(void)anInstanceMethod {
}
@end

And then in Swift, if I have this:

let a = MyClass()
let b = AnotherClass()
myFunc(a)
myFunc(b)

I want myFunc to be able to call aClassMethod on the object it receives.

Reason: I'm creating classes to serve as models to store data. Each model class has a string name, which is the same for each instance, hence the class method. I pass around these instances, but I want their names, to put inside a URL.

Upvotes: 0

Views: 91

Answers (2)

Thijs
Thijs

Reputation: 717

Got it!

func myFunc(obj: MyProtocol) {
    object_getClass(obj).aClassMethod()
}

Upvotes: 0

sweepy_
sweepy_

Reputation: 1331

You're trying to call a class method from an instance of this same class, which is not possible. Instead you can either callMyClass.aClassMethod() or obj.anInstanceMethod().

MyClass() acts as an initializer. When using it, you're creating a new instance of your class on which you can only use instance methods.

Upvotes: 1

Related Questions