2011-10-23 95 views
0

问题:当从另一个类调用该方法时,某个类的变量被忽略。实例方法无法读取类实例变量

基本上:我有A类,B类。我也有方法A,方法B,每个都在它们各自的类中。

当从B类方法B调用方法A时,我可以很好地使用NSLog值,但是我无法访问A类中包含的NSMutableArray。这是我的问题。

// Class B 
- (id)init 
{ 
    self = [super init]; 
    if (self) { 
     // Initialization code here. 
     foodListingObj = [[FoodListing alloc] initWithNibName:@"FoodListing" bundle:nil]; 
    } 


    return self; 
}  

- (void)toggleImage //Method B in Class B { 

    [foodListingObj didToggle:self.indexOfToggledCell]; 
    } 

    // Method in Class A 
    - (void)didToggle:(NSIndexPath *)toggledIndexPath{ 
     //[_toggledIndexArray addObject:toggledIndexPath]; 
      [_toggledIndexArray addObject:@"Anything"]; 
    } 

    // Method in Class A 
    - (void)checkArray{ 

      // Log the count of the array 
      // it always says 1 because I intialize the array 
      // then add an an object like so [_toggledIndexArray [email protected]"hi"]; 
     // in my ViewDidLoad Method. Hence it appears that the array is still around 
      // (not deallocated), but yet my method cannot seem to touch it... 
      NSLog(@"%i",[_toggledIndexArray count]); 
    } 

    // dealloc for Class A 
    - (void)dealloc{ 
      // I release the array among other things 
      [_toggledIndexArray release]; 
    } 

阵列(_toggledIndexArray)是在头声明的属性,并在A类的viewDidLoad与

_toggledIndexArray = [[NSMutableArray alloc] init]; 

错误被初始化的事实是,方法A似乎并不影响阵列这是我不知道的原因。

回答

3

从上面的代码看来,您的问题是您每次调用toggleImage方法时都会创建FoodListing的新实例。

这真的是你打算做的吗?如果是这样,在这种情况下,ViewDidLoad不会被调用,因为您只是视图控制器而不是使用initWithNibName,所以除非您在自定义loadView方法中执行某些操作,否则不会将成为一个加载的视图。

但是,我不希望你每次都想创建一个新的实例,你的代码的含义是FoodListing对象已经存在并且已经填充了数组。

所以,无论“class b”是什么,声明一个FoodListing类型的属性。将其设置为您的FoodListing视图控制器(这可以在创建或呈现类b时,或者在首次创建食物列表对象时,您没有给出足够的上下文让我说)。调用属性中的对象的方法,而不是创建一个新的方法。

+0

我编辑我的问题上面的一些修改后的代码进行测试。这有助于你回答这个问题吗?从现在开始进行更多的测试,我意识到我无法在didToggle方法中执行任何功能。从我的toggleImage类(类B)调用它似乎会导致问题。并非常感谢您的快速和有益的回应! – Apollo

+0

感谢您更新代码。我的答案保持不变:)。为什么每次都要实例化一个新的FoodListing对象? “b类”需要有一个属性或伊娃指向A类的“真实”实例。 – jrturton

+0

我明白你现在说的是什么。你如何使用Class B中的属性指向一个类的实例?再次感谢您的帮助! – Apollo

0

您需要将B类中的FoodListing对象维护为类变量,而不是始终在toggleImage函数中分配/初始化它。也许可以

if(self.foodListing==nil) { //alloc/init it}else{ //do your thing here.}