开发者

NSMutable String "Out of scope"

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 disp开发者_运维知识库lay 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?


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.


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...


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.


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.


what cell style did you used?

if (cell == nil) {
  cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
                                 reuseIdentifier:BasicCellIdentifier] autorelease];
}

perhaps this will help you

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜