Установить атрибут только для чтения в ObjC - PullRequest
0 голосов
/ 09 ноября 2011

Есть ли способ установить значение атрибута только для чтения в Objective-C?На самом деле мне все равно, насколько неприятен код, если он больше не стабилен.

1 Ответ

1 голос
/ 09 ноября 2011

Не берите в голову мой комментарий, вот два способа сделать это:

@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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...