I have a instance variable mTeacher in my School class:
@interface School : NSObject {
Teacher *mTeacher;
}
@end
In implementation file, I have method - (Teacher *)getTeacher which is supposed to return either the existing teacher instance if there is one or create one and return it:
- (Teacher *)getTeacher {
if (mTeacher != nil) {
return mTeacher;
}
return [[Teacher alloc] init];
}
There could be multiple other instance methods calling this method to get the Teacher instance & assign to mTeacher instance variable:
- (void)methodOne {
mTeacher = [self getTeacher];
...
}
- (void)methodTwo {
mTeacher = [self getTeacher];
...
}
So, if one of the method assigned already an instance of Teacher to mTeacher, the other method when calling [self getTeacher] would end up with mTeacher = mTeacher underneath (because - (Teacher *)getTeacher method simply returns mTeacher in this case). My question is , is it fine in objective-C ? Any potential issues with my getTeacher method?
initmethod and use it where needed rather than trying to set it multiple times? (On style: it would be more in keeping with Objective-C to maketeachera property rather than an explicit variable. Then, along with my suggestion aboutinit, the "getter" would disappear from your code.)mTeacheris nevernil, why don't you initialize it in theSchool'sinitmethod ? Also, you should check this out Properties in Objective-c