0
#import <Foundation/Foundation.h>

@interface Engine : NSObject {
    NSMutableString *mutableName;
}

@property (assign)  NSMutableString *mutableName;

@end

为什么我的 ivarengine.name不能使用这种简单的NSMutableString方法?mutableNameNSMutableString并且 已经正确地用@propertyand实现了@synthesize

#import "Engine.h"
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    Engine *engine = [[Engine alloc]init];


  #import "Engine.h"
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Engine *engine = [[Engine alloc]init];

engine.mutableName = @"Jones";
[engine.mutableName insertString:@"Mrs." atIndex:0];
NSLog(@"Full name is %@", engine.mutableName);

}

    [pool drain];
    return 0;
}

#import "Engine.h"

@implementation Engine

@synthesize mutableName;

@end

#import "Engine.h"
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    Engine *engine = [[Engine alloc]init];

    engine.mutableName = @"Jones";
    [engine.mutableName insertString:@"Mrs." atIndex:0];
    NSLog(@"Full name is %@", name);

    [pool drain];
    return 0;
}
4

1 回答 1

1

您还没有显示您的代码,但我怀疑您所做的是声明了这两个属性namemutableName实现了它们以在后台使用相同的 ivar。在这种情况下,您的mutableName属性虽然声明为NSMutableString,但实际上返回的NSString是分配给该name属性的 。如果这是您正在做的事情,并且您确实希望它以这种方式工作,那么您需要将name访问器更改为如下所示(假设_name是支持 ivar):

- (NSString *)name {
    return [[_name copy] autorelease]; // take a snapshot of the string
}
- (void)setName:(NSString *)name {
    [_name release];
    _name = [_name mutableCopy];
}

这样,字符串在后台保持为可变,但在使用name访问器时作为不可变字符串返回。

于 2011-10-26T18:16:39.493 回答