Reputation: 31
First, I have thoroughly researched this and not been able to find anything matching what I'm looking for.
My problem is this: I have a string property created in Class1 and then synthesized as shown below.
@interface Class1 : UIViewController
{
NSString *testvar;
}
@property (nonatomic, retain) NSString *testvar;
@end
@implementation Class1
@synthesize testvar
- (void)viewDidLoad
{
[super viewDidLoad];
self.testvar = @"Test variable";
}
@end
This works fine for defining the variable/property's value as it works in a test UIAlertView
displayed by the same viewDidLoad
method it is defined in. The problem occurs when the other class, Class2, makes an attempt to retrieve and use the property. The code used in the second class is as follows:
Class1 *foo = [[Class1 alloc]init];
UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @"Title"
message:foo.testvar
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
[foo release];
What happens is that the UIAlertView
displays, but has no message. I believe that the value of the Class1 testvar property is being released before Class2 attempts to retrieve it, or I am setting it incorrectly. I say this because I tried the same thing, but used an int instead of NSString
. I set the int's value to 3 in Class1's viewDidLoad
and when the UIAlertView
displayed, it showed the int's value, but displayed "0", the default value of the int, rather than my set value.
Being relatively new to Objective-C and not yet having an excellent grasp of memory management, I think the error has something to do with where or how I set the value of my property. Any insight would be appreciated. Thanks in advance.
Upvotes: 3
Views: 679
Reputation: 1
You can user Global variable for this.
Declare and define it in one class and you can use it in any other class within the project.
Like you can declare a string in ClassA and you can user it in ClassB.
ClassA:
NSString *textVar = nil;
textVar = @"Your Message";
ClassB:
extern NSString *textVar;
UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @"Title
message:textVar
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
Upvotes: 0
Reputation: 15011
You haven't assigned anything to testvar yet. It will still be a nil object at this point.
You need to go something like
foo.textvar = @"my message";
based on your code above anyway.
BTW you don't need to release the alert at that point. You release it in the delegate method that returns the alert reference.
Could you paste the full code for a better understanding?
Upvotes: 0
Reputation: 1804
You are doing it incorrectly. viewDidLoad method is called only when that view is drawn not when you initialize it in another class.
Define a method in Class1 -(id)init and move your self.testvar = @"Test Variable"; into it. Then it should work as expected.
- (id)init
{
if(self = [super init])
{
self.testvar = @"Test Variable";
}
return self;
}
Upvotes: 6