Mahmud Assamaray Mahmud Assamaray - 3 months ago 6
Objective-C Question

Instance variables with same name in different classes causing compile error

I have two objc .m classes, we'll call them controller1.m and controller2.m. In both controller1.m and controller2.m I have instances of UIAlertController, something like this:


controller1.m


@implementation controller1
UIAlertController *alertController;
//more code
@end



controller2.m


@implementaion controller2
UIAlertController *alertController;
//more code
@end


When I try to build the project, I get the error


linker command failed with exit code 1 (use -v to see invocation)


And the error log looks like this

duplicate symbol _alertController in:
/Users/.../Xcode/DerivedData/AppName-cdtbqibmmbsosrdeyqughefeazaa/Build/Intermediates/AppName.build/Debug-iphonesimulator/AppName.build/Objects-normal/x86_64/controller1.o
/Users/.../Xcode/DerivedData/AppName-cdtbqibmmbsosrdeyqughefeazaa/Build/Intermediates/AppName.build/Debug-iphonesimulator/AppName.build/Objects-normal/x86_64/controller2.o


I changed the names of the instance variables for now and it worked... Why do I have to do this? Does Xcode realize that these variables are being used in the same way (due to their name), and that I should have them declared globally, somehow?

Answer

Your problem is that those variables are not instance variables. They are global variables.

To make them instance variables they need to be in the curly braces of the @implementation block as follows:

@implementation controller1 {
    UIAlertController *alertController;
}

//more code

@end
Comments