tags:

views:

37

answers:

4

I have a singleton initializer which is a class method. I want to set instance variable data from it. How can I do this?

A: 

You need an instance to call an instance method. So, either create an instance and call its methods or use class methods.

Should I change those instance methods to be class methods?

If the methods are not related to an instance, it might be a good idea to change them to class methods.

zvonimir
Thanks. I can call instance methods from the class method, it's the instance variables that are giving me trouble. How do I set values for instance variables in a class method? How could I declare those variables so that they can be used in that class method?
Spanky
Well, since your class is a singleton, you can instantiate it and then access its instance variables.If that is not an option for you, the only other solution I can think of is using static variables, which is usually ugly.
zvonimir
A: 

This init Method For Example. It's the way I do it...

-(id)initWithName:(NSString *)name {
    if(self = [super init]) {
       self.name = name;
    }
    return self;
}

In this case the instance variable needs also to be a property. Else you can't write self.name.

Sandro

Sandro Meier
Groovy, but your method is an instance method "-", I'm trying to get access to instance variables from a class method "+".
Spanky
A: 

Than I don't know what you mean. Do you want to set a instance variable? That's possible. (See example below) But if you want to access one, it's not possible. Because they don't exists in the class. They only exist in an object... Example:

+(YourClass *)YourClassWithName:(NSString *)name {
   if(self = [super init]) {
      self.name = name;
   }
   return [self autorelease];
}

If you didn't mean that, I don't know what you meant. ^^

Sandro Meier
+1  A: 

Instance variables can be accessed with the structure pointer operator.
You don't need properties for that:

+ ( MyClass * )sharedInstance
{
    @synchronized( self )
    {
        if( instance == nil )
        {
            instance       = [ [ self alloc ] init ];
            instance->iVar = @"someValue";
        }
    }
    return instance;
}
Macmade
That works, thanks :)
Spanky