Kirubachari
Kirubachari

Reputation: 688

Cannot init a class object - xcode

I'm new to IOS development. I wrote the implementation file following like this.

   @implementation Utils

   +(id)alloc
   {
         return [self instance];
   }

   +(Utils *)instance
   {

        static Utils *utils = nil;

        if (!utils) {
           utils = [self init];
        }

        return utils;
   }

  -(Utils *)init
  {
       self = [super init];
       if (self) {
           mConst = [Constants instance];
           mCONT_REGEXP = [mConst CONT_REGEXP];
       }
       return self;
   }

When i call

 [Utils instance];

I got the error following Like this:

 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[Utils<0xbff54> init]: cannot init a class object.'

Thanks for your answers.

Upvotes: 0

Views: 2140

Answers (2)

Stavash
Stavash

Reputation: 14304

Are you trying to create a shared singleton instance?

In that case, use the following snippet:

+ (id)sharedInstance;
{
    static dispatch_once_t onceToken;
    static Utils *sharedUtilsInstance = nil;

    dispatch_once( &onceToken, ^{
        sharedUtilsInstance = [[Utils alloc] init];
    });

    return sharedUtilsInstance;
}

It is better to call it "sharedInstance" so that it's more understandable the instance is shared.

Upvotes: 3

user1525369
user1525369

Reputation:

remove your following method

+(id)alloc
   {
         return [self instance];
   }

And write code as/....

   +(Utils *)instance
   {

        static Utils *utils = nil;

        if (!utils) {
           unit = [[unit alloc] init];
        }

        return utils;
   }

Upvotes: 0

Related Questions