問題描述
iVar getter / 方法同名? (iVar getter / method with same name?)
誰能解釋這裡發生了什麼,乍一看,我認為這是不好的做法。我的問題是:在下面的示例中,我是使用 ‑(id)model 為模型創建一個新的 getter(即覆蓋 @property 的原始 getter),還是只是用這個新的同名方法掩蓋 @property getter?< /p>
@implementation PlanetController
@synthesize model;
@synthesize planetLabel_01;
@synthesize planetLabel_02;
@synthesize planetLabel_03;
‑ (id)model {
if(!model) {
PlanetModel *tempModel = [[PlanetModel alloc] init];
[self setModel:tempModel];
[tempModel release];
}
return model;
}
這有意義嗎?
加里。
參考解法
方法 1:
What you are doing is not bad practice. You are not overwriting or masking anything. @synthesize will only synthesize what's needed. In this case, the setter.
方法 2:
As everybody else has said, that's absolutely fine. Your model method is used instead of the synthesized one.
However be cautious: you have implemented a method that is not atomic so your property should have the following declaration:
@property (nonatomic, retain) id model;
otherwise it is lying about its implementation.
方法 3:
You've implemented your own accessor for the model property. That's a perfectly valid thing to do. You can verify that it's your implementation that is executed when you do either aPlanetController.model
or [aPlanetController model]
.
方法 4:
It looks OK to me, but you can always check it by printing out the method names at run‑time.
#import <objc/objc.h>
#import <objc/runtime.h>
#include "SFUtility.h"
/*!
@abstract spits out the objc/runtime.h information for the class
*/
void SFInvestigateOBJC(id obj) {
unsigned int total_method_count = 0;
Method * method_list = class_copyMethodList(object_getClass([obj class]), &total_method_count);
@try
{
SFLog(@"ClassName: %s", class_getName(object_getClass([obj class])));
SFLog(@"ClassName: %@", [obj class]);
uint method_counter = 0;
for (method_counter = 0; method_counter < total_method_count; method_counter++)
{
Method method = method_list[method_counter];
// check if method the KVC getter you are interested in
SFLog(@"Method: %s", sel_getName(method_getName(method)));
}
NSDictionary *props = [[obj entity] propertiesByName];
for (NSString *s in [props allKeys]) {
SFLog(@"KVC: %@", s);
}
} @catch (NSException *e) {
SFError(@"Exception: %@", [e description]);
}
@try {
SFLog(@"Entity: %@",[[obj entity] name]);
SFLog(@"EntityClassName: %@", [[obj entity] managedObjectClassName]);
} @catch (NSException * e) {
SFError(@"Exception: %@", [e description]);
}
}
(by fuzzygoat、hooleyhoop、JeremyP、Costique、Stephen Furlani)