Objective C, and NSMutableString

1.5k views Asked by At

Header File:

@interface Picker : UITableViewController <NSXMLParserDelegate> {
    NSMutableString *currentRow;
}
@property (nonatomic, retain) NSMutableString *currentRow;

@end

Implementation File:

#import "Picker.h"

@implementation Picker

@synthesize currentRow;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        currentRow = [[NSMutableString alloc] initWithString:@"VehicleYear"];
    }
    return self;
}
@end

After debugging this and stepping into where currentRow gets initialized with string. Step over the statement then hover over currentRow and value says "Invalid Summary". It would seem that it gets a pointer as i get an address reference something like 0x33112 not actual memory reference. No matter what I do I can't get a valid string in this property, so all of my comparisons are failing. What am I doing wrong?

2

There are 2 answers

4
Phil Willoughby On BEST ANSWER

I don't know if this has something to do with it, but if you read the documentation for the initWithString: method it returns an instance of a subclass of NSString which may or may not be an instance of NSMutableString

Try this instead, it will do what you want:

currentRow = [@"VehicleYear" mutableCopy];

Also, 99% of the time you want a string property of a class you want to declare it as:

@property(readwrite,copy)NSString *name;

If you declare a readwrite string property as anything other than copy then whoever sets it can change their string and affect your object's internal state, which is usually not what you want. If the original string is not mutable then its copy method does a retain anyway so there is no performance lost in the case where it mattered.

If you want a mutable string internally that no external user can change you probably want to declare the property like this:

@property(readwrite,copy)NSString *name;

And then implement -name and -setName: yourself so that you can call -mutableCopy to set it and -copy in the getter so that they cannot change your internal state. I have written extensively about this on my blog.

Note that this

@property(readwrite,copy)NSMutableString *name;

Doesn't do what anyone wants when you @synthesize the accessors as the setter invokes -copy and gets an NSString which is not an NSMutableString as a result.

0
Tony On

I sometimes get incorrect information from the visual debugger. In the gdb console, you can type "print-obj currentRow" and it should give you better information.

One thing to make sure is that you're debugging a build with optimizations turned off (i.e., Debug, not Release, configuration), otherwise the code doesn't map exactly onto the compiled instructions.