Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Objective-C instancetype method in Swift?

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

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

and implementation like this

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

Now I want to call this initWithObjHavingData in Swift

var objData = CustomObjectHavingData()

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

like image 364
Dhvani Puar Avatar asked Dec 24 '22 18:12

Dhvani Puar


2 Answers

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.

Here is how you can do it,

@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

In Swift, you can simply call it like this,

  let myCustomObject = CustomObjectHavingData(objHavingData: someData)

The name is quite inappropriate though.

like image 189
Sandeep Avatar answered Dec 28 '22 09:12

Sandeep


If you want to call the init method without any parameter with the requirements I posted in the question, we have to write the init method like this:

@interface CustomObjectHavingData : NSObject

@property (nonatomic, strong) NSData *objWithData;

- (id)init;
@end

And implement it like this

@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

Then, you can call this from swift like this:

var objData = CustomObjectHavingData()

It will by default initialize all the objects.

like image 34
2 revs, 2 users 99% Avatar answered Dec 28 '22 10:12

2 revs, 2 users 99%