ivar不会响应NSMutableString方法

时间:2011-10-26 17:40:00

标签: objective-c cocoa properties instance-variables nsmutablestring

#import <Foundation/Foundation.h>

@interface Engine : NSObject {
    NSMutableString *mutableName;
}

@property (assign)  NSMutableString *mutableName;

@end

为什么我的ivar engine.name无法使用这种简单的NSMutableString方法? mutableNameNSMutableString,已使用@property@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;
}

1 个答案:

答案 0 :(得分: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访问器时作为不可变字符串返回。