views:

48

answers:

3

There are two classes, let's call them Class A and Class B.

Also, in class B, there's a NSMutableArray called arrayB.

@interface A {
   // for reference functions in B
   B *obj;
}
@property (assign) B *obj;
- (void) addObject: (id) objectB;

And I access B by calling:

obj = [[B alloc] init];

Here's definition of B:

@interface B {
  NSMutableArray *arrayB;
}
@property (assign) NSMutableArray *arrayB;
- (void) printArray;

Now, I tried to add objects to arrayB by functions of A:

[self addObject: objectB]

- (void) addObject: (id) objectB {
   [obj.arrayB addObject:objectB];
   NSLog(@"%@", obj.arrayB);
   // here prints arrayB with objectB
}

However when I tried to access the objects again in B:

[self.obj printArray];

- (void) printArray {
   NSLog(@"%@", arrayB);
   // now it prints an empty array
}

I have no clue what happened here...

Objects will be auto-retained by NSMutableArray's addObject, don't they?

Why it becomes empty every time? >_<

Please help me, thanks!

+2  A: 

It appears that you never initialize the NSMutableArray in your B object, so your -addObject calls are actually:

[nil addObject:myObject];

which in Objective-C is pretty much the same thing as doing nothing at all.

Seamus Campbell
This would not result in an NSLog that shows an array with objects in it.
Chuck
Since the code presented is incomplete and the output is only described, it was a stab in the dark. And @rain didn't say that the NSLog showed an array with objects...
Seamus Campbell
sorry, because the original code is very large... I tried to simplify the scenario. I have initialized arrayB in B though. QQ
Frost
giving us more code... or at least the part where you create your objects and use them... would be useful. with the class definitions interspersed between bits of your execution path, it's challenging to diagnose.
Seamus Campbell
+2  A: 

It's hard to tell where the bug is with only tiny, context-free snippets of code. But most likely these you're creating two different B objects.

Chuck
Thanks a lot! I figured out when I am doing IBAction, the system init another object and use it instead.
Frost
A: 

NSMutableArray will retain any object you add with addObject, your problem is somewhere else.

NSObject *someObject = [[NSObject alloc] init]; [someMutableNSArray addObject:someObject]; [someObject release];

the only reference to someObject is now in the array.

Antwan van Houdt