gpt4 book ai didi

ios - 使用具有通用 setter 和 ARC 的 Objective-C 动态属性

转载 作者:行者123 更新时间:2023-12-01 19:04:24 24 4
gpt4 key购买 nike

我想将动态属性与通用 getter/setter 一起使用,但似乎在某些情况下 ARC 会在不应该释放对象时释放对象。我在这里给出最简单的代码来说明问题。

有效的代码:

我有一个具有一个动态属性“名称”的 Person 类

@interface Person : NSObject
@property (strong, nonatomic) NSString *name;
@end

在实现中,这 2 种方法具有能够设置人名的最少代码。我删除了代码的 setter/getter 部分。
@implementation Person

@dynamic name;

- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector
{
// Setter signature for a NSString
return [NSMethodSignature signatureWithObjCTypes:"v@:@"];
}

- (void)forwardInvocation:(NSInvocation *)invocation
{
// Get the NSString to set
NSString *s;
[invocation getArgument:&s atIndex:2];

NSLog(@"The string is: %@",s);
}

@end

在我的 UIViewController 中,我有一个按钮:
- (IBAction)OnTestClicked:(id)sender
{
Person *p = [[Person alloc] init];
p.name = @"John Doe";
}

并且测试工作正常。我得到了日志

The string is: John Doe



如果我点击按钮 10 次,我有 10 次正确的日志

问题

如果值 @"John Doe"不是字符串文字,当我再次单击测试按钮时,应用程序将崩溃。

这是一个使用不使用字符串文字的私有(private)属性“defaultName”的示例。
@interface MyViewController ()
@property (strong, nonatomic) NSString *defaultName;
@end

@implementation MyViewController

- (void)viewDidLoad
{
[super viewDidLoad];
self.defaultName = [[NSString alloc] initWithFormat:@"John Doe"];
}

- (IBAction)OnTestClicked:(id)sender
{
Person *p = [[Person alloc] init];
p.name = self.defaultName;
}

如果多次单击测试按钮,我会收到消息

malloc: *** error for object 0xa8257b0: pointer being freed was not allocated



或者

malloc: *** error for object 0x8f68430: double free



似乎 ARC 正在释放强大的属性“DefaultName”。但是因为我使用的是 ARC,所以我无法在 setter 中添加保留...。

我该如何解决这个问题?

谢谢

最佳答案

使用 __unsafe_unretained应该解决问题:

- (void)forwardInvocation:(NSInvocation *)invocation
{
// Get the NSString to set
__unsafe_unretained NSString *s;
[invocation getArgument:&s atIndex:2];

NSLog(@"The string is: %@",s);
}

因为 getArgument:只是将参数复制到给定的缓冲区中,没有
保留它。

关于ios - 使用具有通用 setter 和 ARC 的 Objective-C 动态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20645705/

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