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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With