【问题标题】:Set readonly attribute in ObjC在 ObjC 中设置只读属性
【发布时间】:2011-11-09 03:57:21
【问题描述】:

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

【问题讨论】:

标签: objective-c cocoa-touch cocoa properties readonly


【解决方案1】:

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

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

【讨论】:

  • 这也是我尝试过的。我有没有写过这样的访问器:synthesize blabber = _blabber,我需要使用键 _blabber 设置值吗?
  • 没错。您指定 ivar 的名称;属性名称与其没有固有联系——例如,您可以写成@sythesize peanutButter = jelly;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
相关资源
最近更新 更多