Reputation: 1295
I am having some issue about naming overridings of static variables in objective-c.
My .h file is:
#import <Foundation/Foundation.h>
@interface FetchClass : NSObject
+ (void)initWithNSManagedObjectContext:(NSManagedObjectContext *) managedObjectContext;
@end
And my .m file is:
static NSManagedObjectContext * managedObjectContext;
@implementation FetchClass
+ (void)initWithNSManagedObjectContext: (NSManagedObjectContext *) managedObjectContext{
FetchClass.managedObjectContext = managedObjectContext;
}
However, I get the error
"Property managedObjectContext not found on object of type FetchTasks"
So, the problem is, function argument managedObjectContext
is of course overriding the static variable of the same name. That is why I have to get the static variable through Class.staticVariableName. But this time I get error as I mentioned above.
However If I change the static variable name to some other name , like:
static NSManagedObjectContext * managedObjectContextOtherName;
@implementation FetchClass
+ (void)initWithNSManagedObjectContext: (NSManagedObjectContext *) managedObjectContext{
managedObjectContextOtherName = managedObjectContext;
}
It works perfectly. My question is that, how to use these variables (static variable and function argument variable) if they have same name?
Upvotes: 0
Views: 1324
Reputation: 53000
A static variable, like your managedObjectContext
, is the closest thing to a class variable that Objective-C provides but it is not the same thing and this is why you get errors doing what you are trying - you cannot resolve your reference by qualifying it with the class name.
In (Objective-)C a static variable declared outside of any function/method has global lifetime and file scope - i.e. the variable always exists but is only visible from within the same source file as its declaration. There is no "file scope" qualifier you can use to resolve ambiguity/hiding when reference a static, any variable with the same name in an inner scope will hide the static.
In your case you can just use:
+ (void)initWithNSManagedObjectContext:(NSManagedObjectContext *)_managedObjectContext
{
managedObjectContext = _managedObjectContext;
}
(And there is no need to change your declaration of initWithNSManagedObjectContext:
in the interface - parameter names are not required to match - so your "public" declaration doesn't require _'s in the names if you don't wish it to.)
Upvotes: 2
Reputation: 80265
Method arguments and instance variable should have different names. When they are the same, the compiler should warn you that it using the method variable.
Upvotes: 0