0

I have Three class A ,B and C.

@interface ClassA

@property (nonatomic,strong) NSMutableArray *classCArray;

@end

@implementation ClassA 
...
@end

@interface ClassB

@property (nonatomic,strong) NSMutableArray *classCArray;

@end

@implementation ClassB
...
@end

@interface ClassC

@property (nonatomic,strong) NSString *name;

@end

@implementation ClassC
...
@end

Then I create instance "a" of Class A, set "a" variable classCArray ,and pass a.classArray to "b"(instance of ClassB).

ClassA *a = [ClassA alloc] init];
ClassC *cInClassA = [ClassC alloc] init];
cInClassA.name = @"jack";
[a.classCArray addObject:c];

ClassB *b = [ClassB alloc] init];
b.classCArray = a.classCArray;
ClassC *cInClassB = b.classCArray[0];
cInClassB.name = @"Bob";

After above code , cInClassA.name changed.(eauqls "Bob") I don't hope this happen. How I can do ?

1 Answer 1

2

You seem to be assuming that assignment copies objects, it does not. A variable, such as your a, can only ever store a reference to an object and assignment copies the reference.

Your code creates 4 objects: instances of ClassA and ClassB referenced by a and b respectively; a single instance of NSMutableArray referenced by both a.classCArray and b.classCArray; and a single instance of ClassC referenced by the mutable array and variables cInClassA and cInClassB.

If you wish to create a copy of an object use the method copy, or for a mutable copy of a mutable object use mutableCopy.

HTH

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you.I implemented - (id)copyWithZone:(NSZone *)zone;for ClassC(this is a NSCopying method in cocoa),then use [myObject copy],it worked!.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.