On Jul 22, 2008, at 8:33 PM, Jeff Brown wrote:

What do I need to do in the following code to get theString to take the value I'm giving it in foo i.e. "Hi there"?

- (void) aMethod
{
   NSString* theString = @"";
   [self foo:theString];
}

- (NSString*) foo:(NSString*)aString
{
   NSString* stringB = @"Hi there";
   aString = stringB;
}

If you're just inquiring about how to use the language, I think you're looking for:

- (void) aMethod
{
NSString* theString = nil; // No sense initializing it with a pointer to a string, when you're about to reassign it. [self foo:&theString]; // Don't pass the pointer theString, pass the pointer to the pointer theString so that -foo: can write through the pointer-to-pointer to modify the pointer. Makes sense? ;)
}

- (void) foo:(NSString**)aString // Note the extra asterisk, which establishes an additional level of indirection
{
*aString = @"Hi there"; // Use the asterisk to dereference the pointer-to-pointer to modify the pointed-to pointer
}


However, that's a pretty uncommon technique when using Cocoa. More common would be for a method to return a string.

Also, keep the memory management guidelines in mind. They are obscured a bit in trivial examples like this, which only involve string literals. The convention is that callers of the -foo: method, since they are not invoking +alloc, +new, -copy..., or -mutableCopy... need not concern themselves with releasing the returned object. So, - foo: must be implemented to take care of that itself, often by making sure the returned object has been autoreleased.

Lastly, the naming conventions for a method like -foo: would be to prefix it with "get". Something like "getTitle:". Again, though, more common would be just a "title" method which returned the title rather than outputting it via a by-reference parameter.

Cheers,
Ken
_______________________________________________

Cocoa-dev mailing list ([email protected])

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [EMAIL PROTECTED]

Reply via email to