tags:

views:

69

answers:

3

I am trying to create an object only instantiatable through a factory method. I prevented init being used by throwing an exception (see Creating a class with no init method). However this meant that I had to create a new method secretInit to use in the factory method.

//Factory method
- (URLReqs *)buildURLReq:(NSString *)location
{
    URLReqs *tmp=[[URLReqs alloc] secretInit];
    tmp.str=location
    return tmp;
}

- (id) secretInit{
    return [super init];
}

This method is messy and while we can avoid declaring secretInit in the header file, someone could still access it. Is there a nicer solution?

One idea is to try calling init on the super object of URLReqs directly rather than creating a function to do it.

A: 

The solution is to use a category on your object to hide the secret initialization method.

Private Methods through categories

What goal are you trying to accomplish? There might be a better solution than this.

kubi
This doesn't actually hide the method any more than not declaring it. It simply allows other methods within the class to know of its existence and so you don't get a compiler warning.
Casebash
A: 

It only exposes it if it's referenced in the header file.

No, wait. I should state that another way. There's no better way to hide it than to not declare it in the header file. Private methods don't exist in Objective-C.

zneak
+1  A: 
dreamlax
Why don't I want to use this method?
Casebash
I'm not sure why I told you not to use it . . .
dreamlax
OH! It came to me now. I was not going to recommend it because this is specific to the Apple runtime. If by some miracle `GNUstep` became bearable or alternative runtimes become available, then this method may not be usable for those runtimes. I assume you are targeting Mac OS X and/or iPhone (I'm not sure if this will work on iPhone), but since you only tagged your question `objective-c` I wanted to leave a warning. Then I forgot what I was writing about and partially finished my thought at the end of my answer.
dreamlax