Custom designated initializer with BOOL parameter and exception?

My question is probably very simple to answer. I have a custom written designated initializer that gets in a BOOL parameter.

In it, I want to check whether there was a BOOL passed or something else. If something else, I want to raise an exception.

I also want to override the default init and point it to my designated intializer instead of calling super, and pass a nil in there so that the user gets the proper exception when he is not using the designated initializer.

-(id)init
{
  return [self initWithFlag:nil];
} 


-(id)initWithFlag:(BOOL)flag
{
    //get the super self bla bla

    if (flag IS-NOT-A-BOOL)
    {
        //raising exception here
    }
    //store the flag

    return self;
}

What should be in place of IS-NOT-A-BOOL?

Answers


BOOL in objective c can result in either YES or NO, and everything will be casted to one of those values. How about using an NSNumber containing a bool value? Like:

 -(id)initWithFlag:(NSNumber *)flag
{
    //get the super self bla bla

    if (!flag) // Check whether not nil
    {
        //raising exception here
        [NSException raise:@"You must pass a flag" format:@"flag is invalid"];
    }
    //store the flag
    BOOL flagValue = [flag boolValue];

    return self;
}

In this case you could call the method like this

[self initWithFlag:@YES]; // or @NO, anyway, it won't throw an exception

or this

[self initWithFlag:nil]; // it will throw an exception

Need Your Help

Resizing text to fit inside a static div

javascript php resize

Basicly I want a text to resize depending how long the text is. If I wrote "WWWWWWWW" it would be resized to fit inside the 100px div.

How to add data in class within another class

c# oop class

I have one class like below. I want to send one Messageformat like this for one webservice, so I need to add values to Attributecollection and Input.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.