gpt4 book ai didi

objective-c - 在 ObjC 中设置只读属性

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

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

最佳答案

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

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

关于objective-c - 在 ObjC 中设置只读属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8060160/

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