通过引用传递指针并使用它

时间:2011-05-16 14:41:04

标签: iphone objective-c pointers

我试图通过引用从A类到B类的对象来传递指针。在B类中,我希望将此指针指定给ivar并对其进行读写。

这是给我错误的代码(无关紧要)。这是我第一次尝试使用指针,所以请纠正我的理解。

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;
}

2 个答案:

答案 0 :(得分:2)

请不要在这里使用双指针。你不应该处理那样的事情。 这是一种更简单的方法:

ClassA实例中:

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

当您以这种方式定义ClassB时: 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

答案 1 :(得分:1)

initWithAPointer:方法中的分配应该只是:

nameFromClassA = name;

那就是说,这个代码模式闻起来很糟糕。你想要完成什么样的高级目标?