如何在Swift中调用Objective-C实例类型方法?

时间:2015-05-26 13:16:36

标签: ios objective-c swift

我有一个Objective-C类,如下所示:

@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()

这给我的回报是零。请帮助我在这里调用上面的init方法。

3 个答案:

答案 0 :(得分:8)

你不应该在Objective C中编写类似的初始化器。或者你应该只使用init,或者如果你在构造函数中传递参数,那么只有你可以命名它。

以下是如何做到的,

@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中,你可以简单地这样称呼它,

  let myCustomObject = CustomObjectHavingData(objHavingData: someData)

这个名字很不合适。

答案 1 :(得分:1)

如果你想在没有任何参数的情况下调用init方法,并且我在问题中发布了这些要求,我们必须像这样编写init方法:

@interface CustomObjectHavingData : NSObject

@property (nonatomic, strong) NSData *objWithData;

- (id)init;
@end

并像这样实施

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

@implementation CustomObjectHavingData

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

  return self;
}

@end

然后,你可以像这样从swift中调用它:

var objData = CustomObjectHavingData()

默认情况下会初始化所有对象。

答案 2 :(得分:0)

您可以使用此功能:

+ (Common *)sharedInstance
{

    static Common *sharedInstance_ = nil;
    static dispatch_once_t pred;

    dispatch_once(&pred, ^{
        sharedInstance_ = [[Common alloc] init];
    });   
    return sharedInstance_;
}

之后拨打

var com_obj:Common!

com_obj = Common.sharedInstance() com_obj.anyfunc(..)