How to access a variable from inner class

2020-04-07 04:48发布

 //MainClass.m 

 @interface InnerClass : NSObject{

 }
 @end

 @implementation InnerClass

 -(void)run{
      while(isActive){//want to access this variable which defined in MainClass
      //do something
      }
 }

 @end

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

 @implementation MainClass


 @end

I have MainClass and it has an inner class (InnerClass). I want to access the boolean type variable (isActive) defined in MainClass class from the inner class. What I am trying to do is that the inner class will run on a separate thread and will keep checking the isActive variable on the main class and if isActive is false then it will stop running the new thread.. Thanks in advance...

标签: objective-c
2条回答
老娘就宠你
2楼-- · 2020-04-07 05:40

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.

查看更多
▲ chillily
3楼-- · 2020-04-07 05:41

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
查看更多
登录 后发表回答