如何在 Swift 中调用 Objective-C 实例类型方法? [英] How to call Objective-C instancetype method in Swift?

查看:64
本文介绍了如何在 Swift 中调用 Objective-C 实例类型方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的 Objective-C 类:

I have an Objective-C class which looks like this:

@interface CustomObjectHavingData : NSObject
@property (nonatomic, strong) NSData *objWithData;
 - (instancetype)initWithObjHavingData;
@end

和这样的实现

@implementation CustomObjectHavingData
- (instancetype)initWithObjHavingData{
if (self = [super init]) {
    NSString *str = @"This is simple string.";
    self.objWithData = [str dataUsingEncoding:NSUTF8StringEncoding];
}
return self;
}
@end

现在我想在 Swift 中调用这个 initWithObjHavingData

var objData = CustomObjectHavingData()

这对我返回 nil.请帮助我如何在此处调用上述 init 方法.

This returns nil to me. Please help how I can call the above init method here.

推荐答案

你不应该像在 Objective C 中那样编写初始化程序.要么你应该让它只是 init 要么如果你在构造函数中传递参数那么只有你可以否则命名.

You are not supposed to write initializer like that in Objective C. Either you should have it just init or then if you are passing argument in constructor then only you can name it otherwise.

你可以这样做,

@interface CustomObjectHavingData : NSObject

@property (nonatomic, strong) NSData *objWithData;

- (instancetype)initWithObjHavingData:(NSData *)data;

@end


@implementation CustomObjectHavingData

- (instancetype)initWithObjHavingData:(NSData *)data
{
    if (self = [super init]) {
        _objWithData = data;
    }

    return self;
}

@end

在 Swift 中,你可以简单地这样称呼它,

In Swift, you can simply call it like this,

  let myCustomObject = CustomObjectHavingData(objHavingData: someData)

不过这个名字很不合适.

The name is quite inappropriate though.

这篇关于如何在 Swift 中调用 Objective-C 实例类型方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆