2

对于这段示例代码中发生的事情,我有点困惑。我正在创建 C 结构“AUGraph”的名为“processingGraph”的属性。然后我将此结构传递给Objective C方法 [self createAUGraph:_processingGraph];

然后我接受这个论点 - (void) createAUGraph:(AUGraph) graph { NewAUGraph (&graph); ......并创建结构。

但是,这似乎并没有像我认为的那样在属性名称“_processingGraph”处创建结构。

为什么是这样?通过将结构传递给目标 C 方法,它只是创建一个副本吗?在哪种情况下,我将如何在方法中传递对结构的引用?

完整代码:

@interface AudioStepper ()
@property (readwrite) AUGraph processingGraph;

@end

@implementation AudioStepper

- (id) init{
if (self = [super init]) {
    [self createAUGraph:_processingGraph];
}
return (self);
}
- (void) createAUGraph:(AUGraph) graph {
NewAUGraph (&graph);
CAShow (_processingGraph); //no struct?
}

@end
4

2 回答 2

3

graph is not a pointer in your method, so it is getting copied to a new memory location, apart from the original variable. It is like passing in an int or float. This is what is called passing by value.

The C method, however, is using pass by reference. It takes the pointer to graph rather than copying the value.

Since this is an ivar, you can access the pointer to _processingGraph directly:

- (void) createAUGraph {
    NewAUGraph (&_processingGraph);
    CAShow (_processingGraph);
}

Or, if you need to pass in different graphs at different times, you want the method to take a pointer to an AUGraph, use pass by reference:

- (void) createAUGraph:(AUGraph*) graph {
    NewAUGraph (graph);     // Since graph is now a pointer, there is no
                            // need to get a pointer to it.
    CAShow (_processingGraph);
}

And call the method like so:

[self createAUGraph:&_processingGraph];

While that fixes the arguments, be sure to read danh's answer below for a better way to create structs.

于 2013-05-21T00:00:14.310 回答
2

我看到你已经接受了一个答案。很高兴它正在工作。当您接受时,我正在撰写此建议,我认为这仍然是个好建议....

从objective-c CG结构中获取提示,例如CGPoint,并以这种方式定义您的结构:

// I've made up an AUGraph, since I don't know what yours looks like

typedef struct {
    // whatever is in here, say it's two ints
    int foo;
    int bar;
}AUGraph;

让您的属性分配...

@property (assign, nonatomic) AUGraph processingGraph;

而且,最重要的是,以这种方式声明您的创建函数。(这会更快,并且阅读起来更像其他库函数......

static inline AUGraph AUGraphMake(int foo, int bar) {
    AUGraph aug;
    aug.foo = foo;
    aug.bar = bar;
    return aug;
}

这是打印功能的外观...

static inline NSString *NSStringFromAUGraph(AUGraph g) {
    return [NSString stringWithFormat:@"AUGraph: foo=%d, bar=%d", g.foo, g.bar];
}

不是它看起来和感觉像原生的东西......

self.processingGraph = AUGraphMake(3,4);
NSLog(@"%@", NSStringFromAUGraph(self.processingGraph));
于 2013-05-21T00:22:44.897 回答