本文介绍了如何为ivar写我自己的setter,即:self.ivar = ...?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是以下问题的后续问题: self.ivar和ivar之间有区别吗? :
This is a follow-up question of: Difference between self.ivar and ivar? :
self.name = @"hello";
我想知道在 magical setter方法内进行的操作.因此,问题是:有人可以发布setter方法的源代码吗? ;-)谢谢!
I would like to know what is done inside the magical setter method. So the question is: could anyone please post the source code of the setter method? ;-) Thanks!
推荐答案
如果没有属性声明(也就是说,您已经手动声明了setter和getter方法),则通常可以这样实现它们:
Without a property declaration (that is, you have manually declared the setter and getter methods), you'd typically implement them like this:
@interface MyClass : NSObject
{
NSString *name;
}
- (NSString *) name;
- (void) setName:(NSString *) name;
@end
@implementation MyClass
- (void) dealloc
{
[name release];
[super dealloc];
}
- (NSString *) name
{
return name;
}
- (void) setName:(NSString *) aName
{
if (aName != name)
{
[name release];
name = [aName retain];
}
}
@end
原子二传手可能看起来像这样:
Atomic setters could look something like this:
- (void) setName:(NSString *) aName
{
@synchronized(self)
{
if (aName != name)
{
[name release];
name = [aName retain];
}
}
}
这篇关于如何为ivar写我自己的setter,即:self.ivar = ...?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!