How to access a variable from inner class

后端 未结 2 1801
面向向阳花
面向向阳花 2021-01-18 07:29
 //MainClass.m 

 @interface InnerClass : NSObject{

 }
 @end

 @implementation InnerClass

 -(void)run{
      while(isActive){//want to access this variable which d         


        
相关标签:
2条回答
  • 2021-01-18 08:06

    Objective-C doesn't have inner classes as a language construct, however you can do all sorts of tricky things like hiding both the interface and implementation of the "innerclass" in the .m file of the MainClass and having a hidden factory method (not in the interface) on the MainClass that creates the 'innerclass' with a bool* property assigned to &isActive of the main class.

    MainClass.h

     @interface MainClass : NSObject{
          BOOL isActive;
     }
     @end
    

    MainClass.m

     @interface InnerClass : NSObject{
          BOOL* isActive;
     }
    
     -(id)initWithActive:(BOOL*)isAct){
    
          if (self = [super init]) {
             isActive = isAct;
          } 
          return self;
     }
    
     @end
    
     @implementation InnerClass
    
     -(void)run{
          while(*isActive){//want to access this variable which defined in MainClass
          //do something
          }
     }
    
     @end
    
    
     @implementation MainClass
    
          //Can use [self newInnerClass] to create a new instance of the innerclass
         -(id)newInnerClass{
               return [[[InnerClass alloc] initWithActive:&isActive] autorelease];
          }
    
    
     @end
    
    0 讨论(0)
  • 2021-01-18 08:27

    Objective-C doesn't have inner classes. Consider making isActive a property of MainClass, give InnerClass a pointer to an instance of MainClass, and let InnerClass simply access the property.

    0 讨论(0)
提交回复
热议问题