How to Code Initwithcoder in Swift

How to call initWithCoder?

Add below code in your view class .m file

-(id) initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
// Initialization code
}
return self;
}

And Add file name in view Class as below screen shot.

Sample Image

How to test required init(coder:)?

Production code:

required init?(coder: NSCoder) {
return nil
}

Test:

func testInitWithCoder() {
let archiverData = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWithMutableData: archiverData)
let someView = SomeView(coder: archiver)
XCTAssertNil(someView)
}

Since the required initializer returns nil and does not use the coder, the above code can be simplified to:

func testInitWithCoder() {
let someView = SomeView(coder: NSCoder())
XCTAssertNil(someView)
}

NSGenericException: This coder requires that replaced objects be returned from initWithCoder

I noticed that Xcode was updated in the time between working app and crashing app. I rolled back from Xcode 10.2 to 10.1 and now the crash is gone, app is working fine.

Rolling back was a workaround, not a fix.

The problem was in a pod I used (called Inputmask), the problem is fixed in the pod in the meantime and all works fine now with Xcode 10.2.

Initialising a view controller in Swift

You should do it in a different way. If you use storyboards:

UIViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:identifier];

If storyboard is different

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle:nil];

Or from xib:

MyViewController *controller = [[MyViewController alloc] initWithNibName:nibName bundle:nil];

Or if it is from code totally:

MyViewController *controller = [[MyViewController alloc] init];

Also remove -initWithCoder: method from your code



Related Topics



Leave a reply



Submit