通过引用传递指针到类并使用它
我试图通过引用一个对象的指针从 A 类传递到 B 类。在 BI 类中,希望将此指针分配给 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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请不要在这里使用双指针。你不应该处理这样的事情。
这是一种更简单的方法:
在
ClassA
实例中:当您这样定义
ClassB
时:B.h 类:
B.m 类:
Please, do not use double pointers here. You shouldn't handle things like that.
This is a simpler approach:
In the
ClassA
instance:While you define
ClassB
this way:ClassB.h:
ClassB.m:
initWithAPointer:
方法中的赋值应该是:也就是说,这个代码模式有一种糟糕的设计味道。您想要实现的高级目标是什么?
The assignment in your
initWithAPointer:
method should be just:That said, this code pattern smells of a bad design. What high-level goal is it that you're trying to accomplish?