在ObjC中设置readonly属性

时间:2011-11-09 03:57:22

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

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

1 个答案:

答案 0 :(得分: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;
}