I have 2 classes: classA and ClassB. What I want to do is set NSMutableArray *bar in ClassB and use it in ClassA. While debugging the program the MutableArray is set with the values but when I try to use this values in ClassA the array is 0. Do you know what am I doing wrong or if there is a more efficient way to pass variable values between classes?
Sample code
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开发者_如何学运维);
}
}
Since bar is instance member of ClassA, It will have different instance every-time you create a new object of ClassA. When you create object of ClassA in "connectionDidFinishLoading" method, that WILL be accessible in that method only.
If you are not calling the display method on that same object (from what I can understand, its an IBAction in classA, therefore the Object is completely different) you will not get its value. Write a simple function in ClassA to print the value and call from "connectionDidFinishLoading" method using [classA methodName];
精彩评论