gpt4 book ai didi

objective-c - ivar 不会响应 NSMutableString 方法

转载 作者:行者123 更新时间:2023-12-03 18:00:08 24 4
gpt4 key购买 nike

#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;
}

最佳答案

您还没有显示您的代码,但我怀疑您所做的事情被声明为 namemutableName属性并实现它们以在后台使用相同的 ivar。在这种情况下,您的mutableName属性,同时声明为 NSMutableString ,实际上返回 NSString被分配给name属性(property)。如果这就是您正在做的事情,并且您确实希望它以这种方式工作,那么您需要更改您的 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 时作为不可变字符串返回。访问器。

关于objective-c - ivar 不会响应 NSMutableString 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7906608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com