开发者

How to set an instance variable from a class method in ObjC

开发者 https://www.devze.com 2023-01-07 11:19 出处:网络
I have a singleton initializer which is a class method. I want t开发者_如何学运维o set instance variable data from it. How can I do this?Instance variables can be accessed with the structure pointer o

I have a singleton initializer which is a class method. I want t开发者_如何学运维o set instance variable data from it. How can I do this?


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;
}


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.


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


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. ^^

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号