2011-10-13 22 views
0

我有2個類:classA和ClassB。我想要做的是在ClassB中設置NSMutableArray * bar並在ClassA中使用它。在調試程序時,MutableArray設置了值,但是當我嘗試在ClassA中使用此值時,數組爲0.你知道我在做什麼錯誤,或者是否有更有效的方法在類之間傳遞變量值?在其他類中使用NSMutableArray屬性objective-c

示例代碼

ClassA.h 

@interface ClassA : UIViewController { 
    NSMutableArray *bar; 
} 

@property(nonatomic, retain)NSMutableArray *bar; 
-(IBAction)Display:(id)sender; 

ClassA.m 

// bar initialization 
-(id)init{ 
    self=[super init]; 

    if (self) { 
     bar=[[NSMutableArray alloc]init]; 
    } 
    return self; 
} 

-(IBAction)Display:(id)sender { 

// Trying to display the NSMutableArray set in ClassB 
NSLog(@"%d",[bar count]); 
} 

ClassB.m 

#import "ClassB.h" 
#import "ClassA.h" 

ClassA *classA; 

-(void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    classA=[[ClassA alloc]init]; 

    // Populating the NSMUtableArray of ClassA 
    for (int i=0; i<[array count]; i++) { 
       NSDictionary* dicObjects=[array objectAtIndex:i]; 

       NSString* remoteUrl=[dicObjects objectForKey:@"remote_url"]; 
       [classA.bar addObject:remoteUrl]; 
      } 

    // NSLog the results (It works!) 
    for (NSString *foo in classA.bar) { 
      NSLog(@"%@",foo); 
     } 

} 
+0

你如何檢查在calssA數組是0? – jamapag

+0

這真的是你正在運行的確切代碼嗎?您在'ClassA.m'中缺少'@ implementation'和'@synthesize bar'。 –

+0

從哪裏調用「顯示」功能? – Shri

回答

0

因爲酒吧是ClassA的實例成員,這將有不同的實例創建ClassA的新對象的每次。當在「connectionDidFinishLoading」方法中創建ClassA的對象時,只能使用該方法訪問該對象。

如果你不是在同一個對象上調用顯示方法(從我能理解的,它在classA中的一個IBAction,因此該對象是完全不同的),你將不會得到它的價值。在ClassA中編寫一個簡單的函數,使用[classA methodName]打印值和來自「connectionDidFinishLoading」方法的調用;

+0

謝謝你解決我的問題,我之前還沒有使用過類方法。 – user992354

+0

@ user992354 ..如果您發現該解決方案有用,請考慮upvoting並接受答案.. :) – 2011-10-14 03:40:35

+0

我希望upvote不幸我沒有足夠的聲望。對不起 – user992354