开发者

error on importing a .m implementation file

I was trying to import a .m file to use a static variable declared there in to another class.

#import "Faculty.m"

I got the error "No such file or directory". Now this might be a bad programming practice to declare开发者_StackOverflow社区 variables in .m implementation files, but just out of curiosity, what is the error all about? The .m file does exist right? Why "No such file" then?


If an imported file isn't in the same directory as the file where the import command is, the compiler uses the project's *.hmap file to locate it. This file is automatically generated by Xcode and only contains the locations of *.h files.

Your import command would work (or at least it wouldn't generate a not found error) if the *.m file was in the same directory as the file containing the #import command.


It sounds like your .m file is somewhere other than the current directory and the directories that the preprocessor knows to look for headers. Or it could be that importing Faculty.m creates a circular dependency, which will give that error as well.

But what you're trying to do almost certainly won't even work, even if you get it to compile. Most of the time, importing an implementation file will cause functions, classes and methods to be defined multiple times in your program, which is invalid and will screw up your compilation. But even assuming that doesn't crop up here, you have to keep in mind how #include and #import work — they literally just copy and paste the named file into the current file. This means that if Faculty.m has a static variable named "foo" and that file is imported by Student.m and Administrator.m, then Faculty.m will have one static static variable named "foo", Student.m will have a completely different and unrelated static variable named "foo" and Administrator.m will have still another unrelated static variable named "foo".

The right way to do what you want is to use a non-static variable in Faculty.m, declare the variable extern in Faculty.h, and have the other .m files that need to use the variable import Faculty.h.


Try :

#import "Faculty.h"

With this Falculty files :

// Faculty.h
@interface Faculty : NSObject {
}
+ (VarType*)variable;
+ (void)setVariable:(VarType*)newVariable;
@end

// Faculty.m
#import "Faculty.h"

static VarType* variable;

@implementation Faculty

+ (VarType*)variable {
    return variable;
}

+ (void)setVariable:(VarType*)newVariable {
    if (variable != newVariable) {
        [variable release];
        variable = [newVariable copy];
    }
}
@end


Normally ".m"-files (module) are not imported. Instead you import the ".h" (header) files, which contain the declarations of the classes and methods. These contain enough information to give the compiler an idea how to make everything work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜