1

头文件:

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

@end

实施文件:

#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

在调试这个并进入 currentRow 用字符串初始化的地方之后。跳过该语句,然后将鼠标悬停在 currentRow 上,值显示“无效摘要”。似乎它得到了一个指针,因为我得到了一个地址引用,比如 0x33112 而不是实际的内存引用。无论我做什么,我都无法在这个属性中得到一个有效的字符串,所以我所有的比较都失败了。我究竟做错了什么?

4

2 回答 2

4

我不知道这是否与它有关,但是如果您阅读该initWithString:方法的文档,它会返回一个子类的实例,该实例NSString可能是也可能不是NSMutableString

试试这个,它会做你想做的事:

currentRow = [@"VehicleYear" mutableCopy];

此外,99% 的时间你想要一个类的字符串属性,你想将它声明为:

@property(readwrite,copy)NSString *name;

如果您将读写字符串属性声明为复制以外的任何内容,那么设置它的任何人都可以更改其字符串并影响对象的内部状态,这通常不是您想要的。如果原始字符串不可变,则其复制方法无论如何都会保留,因此在重要的情况下不会损失性能。

如果您在内部想要一个没有外部用户可以更改的可变字符串,您可能希望像这样声明该属性:

@property(readwrite,copy)NSString *name;

然后实现-name-setName:你自己,这样你就可以调用-mutableCopy来设置它并-copy在 getter 中,这样它们就不能改变你的内部状态。我在我的博客上写了很多关于这个的文章。

请注意,这

@property(readwrite,copy)NSMutableString *name;

-copy当您在 setter 调用时 @synthesize 访问器并获得一个不是 NSMutableString 结果的 NSString时,不会做任何人想要的事情。

于 2011-02-11T16:28:10.133 回答
1

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.

于 2011-02-11T16:41:19.350 回答