5

If you define a swift class like this

@objc class Cat {

}

In swift you can just do

var c = Cat()

But how do you make a Cat instance in Objective-C ?

Subclassing NSObject works because you can then "alloc-init" but can we achieve this without subclassing an Objective-C class?

1
  • Maybe this article will help you Commented Apr 29, 2015 at 16:19

3 Answers 3

4

The most direct way is to subclass Cat from NSObject. If you can't do that, you will need to make a class method or a function that returns a Cat.

@objc class Cat {
    class func create() -> Cat {
        return Cat()
    }
}
func CreateCat() -> Cat {
    return Cat()
}


Cat *cat = [Cat create];
Cat *cat = CreateCat();
Sign up to request clarification or add additional context in comments.

Comments

1

In modern objective-c you can call functions like they were properties:

Swift:

class func create() -> Cat {
    return Cat()
}

Obj-c:

Cat *cat = Cat.create;

1 Comment

While it is possible to call class methods this way due to how the compiler is implemented, it is generally bad form to do so. Dot notation is explicitly for accessing properties in ObjC. See "Dot Syntax Is a Concise Alternative to Accessor Method Calls" developer.apple.com/library/ios/documentation/Cocoa/Conceptual/… "Dot syntax is purely a convenient wrapper around accessor method calls."
0

You can declare +alloc in a dummy category (don't need to implement it):

@interface Cat (Alloc)
+ (instancetype)alloc;
@end

and then you can use regular alloc-init on it:

Cat *cat = [[Cat alloc] init];

all without needing to change the Swift code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.