views:

278

answers:

4

I have two NSMutableString objects defined in my viewController's (a subclass of UITableViewController) .h file:

NSMutableString *firstName;
NSMutableString *lastName;

They are properties:

@property (nonatomic, retain) NSMutableString *firstName;
@property (nonatomic, retain) NSMutableString *lastName;

I synthesis them in the .m file.

In my viewDidLoad method - I set them to be blank strings:

firstName = [NSMutableString stringWithString:@""];
lastName = [NSMutableString stringWithString:@""];

firstName and lastName can be altered by the user. In my cellForRowAtIndexPath method, I'm trying to display the contents of these strings:

cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ %@", firstName, lastName];

but this is causing the app to crash as soon as the view controller is displayed. Using the debugger, it seems that both firstName and lastName are "out of scope" or that they don't exist. I'm new to Xcode but the debugger seems to halt at objc_msgSend.

What am I doing wrong?

+1  A: 

make habit of putting self.variableName... and instead of stringWithsString try using initWithString...hope it will solve the problem...BTW you have explained the question very well...

mihirpmehta
A: 

Your cell is loading and accessing firstName and lastName before they are initialized. viewDidLoad is too late, try awakeFromNib or viewWillLoad or whatever it is on iPhone.

Elise van Looij
That would make the values nil, which wouldn't give the expected strings but wouldn't crash either.
smorgan
'Out of scope' is not nil, it means that the compiler hasn't gotten around to assigning any value, nil or not, to the variable in question yet.
Elise van Looij
+4  A: 

The problem is that you need to do:

self.firstName = ...
self.lastName = ...

That will call the auto-generated setter methods, which will retain the values. By just assigning directly, you are bypassing the setters, and as soon as the current autorelease pool is drained the two variables will have dangling pointers.

smorgan
A: 

You can't use:

firstName = [NSMutableString stringWithString:@""];

Since it will deallocate as soon as viewDidLoad execution finishes.

Try:

firstName = [[NSMutableString alloc] initWithString:@""];

Or:

[self setFirstName:[NSMutableString stringWithString:@""]];

And don't forget to release firstName and lastName on dealloc message.

Pablo Santa Cruz