#import <Foundation/Foundation.h>
@interface Engine : NSObject {
NSMutableString *mutableName;
}
@property (assign) NSMutableString *mutableName;
@end
为什么我的ivar engine.name
无法使用这种简单的NSMutableString
方法? mutableName
是NSMutableString
,已使用@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;
}
答案 0 :(得分:1)
您尚未展示自己的代码,但我怀疑您所做的是name
和mutableName
属性,并实施它们以使用相同的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
访问器时作为不可变字符串返回。