如何覆盖单例类中的属性的getter/setter目标C.

0 objective-c ios

我创建了单例类,并将一个类对象(myRecords)作为其中的属性.我想在这个属性的getter/setter中做一些实现处理.

我如何覆盖此属性的getter/setter?

注意:myRecord的初始化不是在单例内完成的.

// singleton.h

@interface mySingleton : NSObject

@property(nonatomic, copy) NSString *name;

@property(nonatomic) myRecords *record;

+(mySingleton *)instance;

@end

// singleton.m
@implementation TRNApplicationContext
+(mySingleton *)instance {

static mySingleton *_instance = nil;

    @synchronized (self) {
        if (_instance == nil) {
            _instance = [[self alloc] init];
        }
    }
    return _instance;
}

-(void) setRecord:(myRecords *)record
{
    self.title = record.name;
    . . .
}

-(myRecords *) record
{
        return self.record;     // Error - EXC_BAD_ACCESS
}

@end

// TestMainViewController.m - Below is Singleton usage

@implementation TestMainViewController

-(void)viewDidLoad
{
 .  .  .
    myRecords *someRecord = [myRecords new];
    someRecord.name = @"test";
    [[mySingleton instance] setRecord:someRecord];
    NSLog(@"value : %@", [[[mySingleton instance] record] name]);
}

@end
Run Code Online (Sandbox Code Playgroud)

Bry*_*hen 5

您有堆栈溢出错误.

你需要改变

-(myRecords *) record
{
    return self.record;  // call this method again and cause infinite recursion 
}
Run Code Online (Sandbox Code Playgroud)

@synthesize record = _record; // usually put this on the line below @implementation
-(myRecords *) record
{
    return _record;     // return the ivar
}
Run Code Online (Sandbox Code Playgroud)

你还需要

_record = record;
Run Code Online (Sandbox Code Playgroud)

setRecord:

  • @ user3020200如果你覆盖_both_ getter和setter,你需要`@ synthesize`.否则它不会为你创造伊娃,因为你可能不需要它. (3认同)