ios - Two class access each other by importing their head file(via #import ) causes error -
two class access each other importing head file(via #import ) causes error?
i have been suggested use @class classname in header file if needing access other classes . i've got principle of why should this. there small sample below, triggers errors like" unknown type name ‘xxxclass’”. mean “#import” doesn’t copy code here ? if not so, why unable detect ‘xxxclass’
i think not cycle retain problem, principle of error ?
============================ person =============================== person.h #import <foundation/foundation.h> #import "dog.h" //@class dog; @interface person : nsobject @property (nonatomic, strong) dog *dog; //error :unknown type name ‘dog' @end person.m #import "person.h" @implementation person - (void)dealloc{ nslog(@"person--dealloc");} @end ============================ dog =============================== dog.h #import <foundation/foundation.h> #import "person.h" @interface dog : nsobject @property (nonatomic, weak) person *person; //error:unknown type name‘person' @end dog.m #import "dog.h" @implementation dog - (void)dealloc{ nslog(@"dog--dealloc");} @end ============================ main =============================== main.m #import <foundation/foundation.h> #import "person.h" #import "dog.h" int main() { person *p = [[person alloc] init]; dog *d = [[dog alloc] init]; p.dog = d; d.person = p; return 0; }
basically, #import makes compile entire text of specified file 1 statement written. when have circular #import statements compiler becomes confused , throws error. why should use @class break cycle.
Comments
Post a Comment