简体   繁体   中英

Must you override init when you create a new designated initializer?

I have read up quite a bit on designated and convenience initializers in objective-c and feel I have a good understanding of how and why they are used. I just have a couple of outstanding questions, well one really.

Say you have a class that inherits directly from NSObject and you create a designated initializer for it.

I realise you can now mark your designated initializer using NS_DESIGNATED_INITIALIZER but I am wondering if that means it forces you to separately, within the same class, first override init with a call to your designated initializers?

Secondly, if you weren't to use this macro, what might the implications be of NOT overriding init explicitly with the call to the designated initializer? I realise the compiler would not know which was the designated initializer, so could anything bad come of this, and is it just good practice to also override init when you create a new designated initalizer for your class?

EDIT: I just want to add further clarification on this question. I have seen examples of good coders not adding a distinct method to override init despite having added a designated initialiser of their own making. When I ask if you should override init I mean in addition to creating your own specific designated initialiser which of course should call its superclass's init method. I have seen a good coder not do this and so I wondered why you would therefore do it.

you can now mark your designated initializer using NS_DESIGNATED_INITIALIZER but I am wondering if that means it forces you to separately, within the same class, first override init with a call to your designated initializer?

Calling any initializer in self will bypass the warning. When I try to call a super.init method I do get the following warning.

Convenience initializer missing a 'self' call to another initializer.

what might the implications be of NOT overriding init explicitly with the call to the designated initializer?

This would mean your object might be missing some important information that it requires to function, or that the app assumes the object always has, and if it doesn't have it, it could cause errors or a crash in your app.

Here is a good explanation of how it works:

http://timekl.com/blog/2014/12/09/objective-cs-designated-secret/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM