I am trying to pass a pointer by reference to an object from class A to class B. In class B I want to assign this pointer to a ivar and read and write to it.
This is the code that gives me errors (does not matter what errors). This is my first try with pointers so please correct my understanding.
Class A
//This is the parameter I would like to pass as a pointer and be able to manipulate from class B
NSString *name = @"Cyprian";
-(void)passAParameter{
ClassB *classB = [[ClassB alloc] initWithAPointer:&name];
...
}
Class B
// ClassB.h
@interface ClassB{
NSString **nameFromClassA;
}
@property(nonatomic,assign)NSString **nameFromClassA;
-(id)initWithAPointer:(NSString **)name;
// ClassB.m
@implementation ClassB
@synthesize nameFromClassA;
-(id)initWithAPointer:(NSString **)name{
*nameFromClassA = *name;
}
//Print the name
-(void)printName{
NSLog(@"Name: %@", *nameFromClassA);
}
//Will this change the name in class A?
-(void)changeNameInClassA:(NSString* newName){
*nameFromClassA = newName;
}
Please, do not use double pointers here. You shouldn’t handle things like that.
This is a simpler approach:
In the
ClassAinstance:While you define
ClassBthis way:ClassB.h:
ClassB.m: