views:

414

answers:

2

I want to send a string from one class to the other:

1) In class1, I add a property to hold the string:

@property (nonatomic, retain) NSString *str; 

2) and a method to send back a string:


-(NSString *)sendBackStr:(NSString *)strURL
{
    NSString *str = [[NSString alloc] stringWithString:strURL];
    return str;
}

3) In class2, I add a property to hold the received string:

@property (nonatomic, retain) NSString *returnStr; 

4) and the following code:

Class1 *c1 = [[Class1 alloc] init]; 
returnStr = [c1 sendBackStr:@"URL"];

But the program stops at returnStr = [c1 sendBackStr:@"URL"]; Any ideas about what's wrong with it?

+1  A: 

stringWithString: is a message that needs to be sent to the NSString class, not an instance of your class (returned via alloc).

The correct code should be:

-(NSString *)sendBackStr:(NSString *)strURL
{
    return [NSString stringWithString:strURL];
}

You might want to familarize yourself more about the idioms around allocation, retention, and autoreleasing of pointers. If you wanted to alloc this string for some reason and return it from the sendBackStr: message, then you would probably want this code:

-(NSString *)sendBackStr:(NSString *)strURL
{
    return [[[NSString alloc] initWithString:strURL] autorelease];
}
Bill Heyman
The alloc isn't returning an instance of "your class" - it's [NSString alloc]. But stringWithString is a class method.
Jane Sales
+1  A: 

stringWithString is a class method returning an autoreleased string. You should be calling it like this:

myProperty = [NSString stringWithString:strURL];

Here I assume your property does a copy, to increment the retain count on the autoreleased string that's returned from the stringWithString method. (Objects returned from alloc calls have a retain count of one and are not autoreleased.) It's more usual to give strings the copy property rather than the retain one - you usually just want your own copy of a string, not a shared reference to a string owned by someone else.

What I also can't understand is why you've written the code like this, unless it's just an example. In class 2, all you need to do is write

returnStr = [NSString stringWithString:@"URL"];
Jane Sales
Thanks for your answer. And yes, this is just a simple test I write to transfer value.
iPhoney