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?

Community
  • 1
  • 1
Frost_Mourne
  • 149
  • 10

1 Answers1

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579