Search code examples
iphoneclass-designdata-transfertransfer

How to transfer values between classes on iPhone?


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?


Solution

  • 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"];