开发者

How to access a variable from inner class

开发者 https://www.devze.com 2023-02-17 13:21 出处:网络
//MainClass.m @inte开发者_StackOverflow中文版rface InnerClass : NSObject{ } @end @implementation InnerClass
 //MainClass.m 

 @inte开发者_StackOverflow中文版rface 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 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.


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

精彩评论

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