0

Forgive me as it is quite basic, but I want to confirm what's the best way out there. I am creating an instance using "initWith" type of approach, using the designated initializer -

(instancetype)initSignUpParamsWithType:....

In the implementation of the designated initializer it goes something like:

   self = [super init];
        if (self) {

            if (type != requiredType) {
                // what needs to be done in this case for raising a proper error? 
               return nil;
            }
            self.type = type;
            self.username = username;
            self.password = password;

Now, in the above method if some param value is NOT what the object seeks, I want to raise an error during the initialization. In Java, we can throw an exception in such cases.

I know we can throw an exception in Objective-C too, but it is not encouraged for such kind of errors. As can be seen discussed here: throwing an exception in objective-c/cocoa

Can someone please guide me to the best practice around this?

1 Answer 1

0

If your goal it to deal with silly programming errors that will easily be found during testing, then the simplest solution is to use NSAssert.

For example:

NSAssert(type == requiredType, @"Bad programmer passed in incorrect type of %d", type);

Use this in place of your if statement. Better yet, make this the first line of the initSignUp... method.

If the method is called with the wrong type, the app will crash showing the message provided in the NSAssert call.

Another option, used by many of Apple's APIs is to throw an NSInvalidArgumentException.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply! I will try and update if that solves the problem.
That solves it, It seems to behave similar to the functionality implemented in its Java counterpart.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.