gpt4 book ai didi

ios - 如何覆盖单例类 Objective C 中属性的 getter/setter

转载 作者:行者123 更新时间:2023-11-28 18:19:01 25 4
gpt4 key购买 nike

我创建了单例类,并在其中有一个类对象 (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

最佳答案

你有堆栈溢出错误。

你需要改变

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

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

你还需要

_record = record;

setRecord 中:

关于ios - 如何覆盖单例类 Objective C 中属性的 getter/setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24593953/

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