Reputation: 16302
I have a struct declared in .m file of Class A:
typedef struct myStruct
{
size_t count;
} myStruct;
And I am trying to pass it as parameter to a method in another class (Class B) in which I #import
the .h file of class A (i.e. #import "myClassA.h"
):
- (void)myMethodWithStructInClassB:(myStruct)aStruct
{
}
I got these error, respectively, when I did:
- (void)myMethodWithStructInClassB:(struct myStruct*)aStruct
Declaration of type struct aStruct will not be visible outside of this function.
- (void)myMethodWithStructInClassB:(struct myStruct)aStruct
Variable has incomplete type myStruct aStruct
I have then tried using #include
instead, still the errors exist.
By the way, what would be the difference using #include
and #import
in Objective-C? I have done some research, while they were answers but they were not helpful for my case here. Some say with #import we prevent double-including the header, but the arguments were not settled between answerers.
I managed to fix the problem only when I did: #import "myClassA.m"
(not .h).
Can some one explain to me the (a) errors above and (b) the difference between the use of #include
and #import
in Objective-C and (c) why importing .m did the trick for me?
In addition, which would be the proper way to do, when passing struct as parameter in Objective-C? i.e. #import
or #include
?
Upvotes: 1
Views: 4317
Reputation: 521
You declared the struct inside an .m file, but you are importing a .h file. Typically, what you want is to declare the struct inside the .h file, and import that to your second class. Don't import a .m file! .m means iMplementation (not sure whether the m really stems from that) and means, that the stuff is only implemented there, but declared elswhere (most of the time). ".h" are interface files, and, as the name states, give the interface of a class. Thus, any symbol that the class wants to declare publicly, you should put inside of the .h file.
#include
just copies all the file's contents to the place where you put the #include
statement. #import
is somewhat more intelligent, as you said, because it imports the code only once for the whole binary. So, in general, always use #import
when using Obj-C.
typedef struct
{
size_t count;
} myStruct;
#import "myClassA.h"
- (void)myMethodWithStructInClassB:(myStruct)aStruct
{
aStruct.count = 42;
}
Upvotes: 1
Reputation: 25459
The difference between #include and #import is that #import always make sure that the file will be imported just once.
The error you have is because you implemented the struce in .m file which make it kind of private, you don't expose it to the other classes. You should move it to .h file if you want to use it in different classes.
The other whiny is this declaration:
- (void)myMethodWithStructInClassB:(struct myStruct*)aStruct
it's fine if you want to have a pointer to the struct but I believe you just want to pass it as parameter, try:
- (void)myMethodWithStructInClassB:(myStruct)aStruct
Upvotes: 3