开发者

Passing a pointer by reference to class and using it

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 ClassA instance:

-(void)passAParameter{
   NSString *name = @"Cyprian";
   ClassB *classB = [[ClassB alloc] initWithAPointer:name];
   ...
}

While you define ClassB this way: ClassB.h:

@interface ClassB{    

    NSString *nameFromClassA;
}
@property(nonatomic,retain) NSString *nameFromClassA; // Retaining it will give you less headaches

-(id)initWithAPointer:(NSString *)name;
@end

ClassB.m:

@implementation ClassB

@synthesize nameFromClassA;

// You should release all retained object when deallocating self
- (void) dealloc {
    [nameFromClassA release];
    nameFromClassA = nil;
    [super dealloc];
}

-(id)initWithAPointer:(NSString *)name{
    if ((self = [super init])) {     // Always init the object from super!
        self.nameFromClassA = name;  // Retain the object calling self.
    }
    return self;
}

//Print the name
-(void)printName{
   NSLog(@"Name: %@", nameFromClassA);
}

//Will this change the name in class A?
-(void)changeNameInClassA:(NSString* newName){
    self.nameFromClassA = newName; // Retain it calling self.
}

@end


The assignment in your initWithAPointer: method should be just:

nameFromClassA = name;

That said, this code pattern smells of a bad design. What high-level goal is it that you're trying to accomplish?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜