开发者

Naming Properties different than their instance var?

开发者 https://www.devze.com 2023-02-13 08:33 出处:网络
I\'m new to objective-c 2.0 (coming from .NET c#) and I discovered the Properties. They are very handy for dealing with the memory management (retain).

I'm new to objective-c 2.0 (coming from .NET c#) and I discovered the Properties. They are very handy for dealing with the memory management (retain).

So I can set the vars in the init method pretty easy like

@property (retain) NSDate *d1, *d2;

and

@synthesize d1, d2;

-(id)init {
    if (self = [super init]) {
        // initialize Properties
        self.d1 = [NSDate date];
        self.d2 = [NSDate date];
    }            
return self;
}

Sometimes I forget (may be because of my .NET background) to use the 'self.' It looks familiar and not really like bad coding. So I might miss it in the future again...

-(id)init {
    if (self = [super init]) {
        // initialize Properties
        d1 = [NSDate date];
        d2 = [NSDate date];
    }            
return self;
}

But this will result in an EXC_BAD_ACCESS violation when the property will be set using self.d1 = [NSDate dat开发者_JAVA百科e]; or from outside objXy.d1 = [NSDate date];

I would appreciate it, when the compiler will warn me about using properties directly and not through the synthesized messages. This could be done easily by naming the instance var different then the property.

Just wondering, if anybody is doing this that way, or in another...? My researches showed, that it is possible, but I need to declare the vars on my own in the header file. For this I would use a prefix (the _ is reserved for the CF) so I would need something bigger like XY_ ... hm... not really so handy...

Why not having an attribute for Properties like (unique) which will generate a instance var with an different name than the Property name... @apple


This is possible and very easy! When you use @synthesize do this:

@synthesize propertyName=_ivarName;

This will create an ivar named _ivarName as if you declared it in your header file.


You've got a good idea, but at the moment you need to declare the variable yourself if you want to use an ivar with a name different from the property name.

0

精彩评论

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

关注公众号