1

I'm a newbie in Objective C, used to write C. Anyway, I have a class called DataProcessing:

DataProcessing.m
...
- (BOOL)MyStringTweaker:(NSString *)strIn : (NSString *)strOut {
    if(some_thing) {
        strOut = [NSString stringWithFormat:@"I_am_tweaked_%@", strIn];
        return true;
    }
    else
        return false;
}
...

From the AppDelegate (OSX Application)

AppDelegate.m
...
NSString *tweaked;
DataProcessing *data_proc = [[DataProcessing alloc] init];
if([data_proc MyStringTweaker:@"tweak_me":tweaked])
    NSLog([NSString stringWithFormat:@"Tweaked: %@", tweaked]);
else
    NSLog(@"Tweaking failed...");
...

This doesn't work, *tweaked is NIL after the call to MyStringTweaker...

What am I missing?

4

1 回答 1

2

Objective-C, like C, is pass-by-value only. You need to change your method signature to be:

- (BOOL)MyStringTweaker:(NSString *)strIn : (NSString **)strOut

and use:

*strOut = [NSString stringWithFormat:@"I_am_tweaked_%@", strIn];

to do the assignment.

Then, where you call it, you need to pass the address of the pointer you want to fill in:

[data_proc MyStringTweaker:@"tweak_me" :&tweaked]

A good explanation is in the comp.lang.c FAQ.

Editorial aside: Why not label the second argument? It looks weird to have it naked like that.

于 2012-12-20T19:28:11.090 回答