在 ObjC 中设置只读属性

发布于 2024-12-14 15:57:49 字数 60 浏览 1 评论 0原文

有没有办法在 Objective-C 中将值设置为只读属性? 实际上我不在乎代码有多糟糕,除非它不再稳定。

Is there a way to set a value to readonly attribute in Objective-C?
I actually don't care how nasty the code is unless it isn't stable anymore.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绮筵 2024-12-21 15:57:51

别介意我的评论,这里有两种方法:

@interface Grimley : NSObject
@property (readonly, copy) NSString * blabber;
@property (readonly, copy) NSString * narwhal;

- (id) initWithBlabber:(NSString *)newBlabber;
@end

@implementation Grimley
@synthesize blabber;
@synthesize narwhal = unicorn;

- (id) initWithBlabber:(NSString *)newBlabber {
    self = [super init];
    if( !self ) return nil;

    // Any object can of course set its own ivar regardless
    // of how the property it backs is declared.
    blabber = [newBlabber copy];
    // Refer to the _ivar_, not the property.
    unicorn = @"One horn";

    return self;
}
@end

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

    Grimley * g =  [[Grimley alloc] initWithBlabber:@"Excelsior"];

    // This is how you get around the property.
    [g setValue:@"Nimitz" forKey:@"blabber"];
    // Again, use the name of the variable, not the property
    [g setValue:@"Pearly horn" forKey:@"unicorn"];

    NSLog(@"%@", [g blabber]);
    NSLog(@"%@", [g narwhal]);

    [g release];
    [pool drain];
    return 0;
}

Never mind my comment, here's the two ways you do it:

@interface Grimley : NSObject
@property (readonly, copy) NSString * blabber;
@property (readonly, copy) NSString * narwhal;

- (id) initWithBlabber:(NSString *)newBlabber;
@end

@implementation Grimley
@synthesize blabber;
@synthesize narwhal = unicorn;

- (id) initWithBlabber:(NSString *)newBlabber {
    self = [super init];
    if( !self ) return nil;

    // Any object can of course set its own ivar regardless
    // of how the property it backs is declared.
    blabber = [newBlabber copy];
    // Refer to the _ivar_, not the property.
    unicorn = @"One horn";

    return self;
}
@end

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

    Grimley * g =  [[Grimley alloc] initWithBlabber:@"Excelsior"];

    // This is how you get around the property.
    [g setValue:@"Nimitz" forKey:@"blabber"];
    // Again, use the name of the variable, not the property
    [g setValue:@"Pearly horn" forKey:@"unicorn"];

    NSLog(@"%@", [g blabber]);
    NSLog(@"%@", [g narwhal]);

    [g release];
    [pool drain];
    return 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文