gpt4 book ai didi

IOS NSMethodSignature 保持为零

转载 作者:行者123 更新时间:2023-11-29 10:56:22 25 4
gpt4 key购买 nike

我最近开始为 IOS 开发并与调用对象作斗争。

我有一个类“Location”,派生自 NSManagedObject(它是 Coredata 模型的一部分)

@interface Location (CoreDataGeneratedAccessors)

- (void)addHasLocationInfoObject:(Info *)value;
...
@end

我还有其他具有类似签名的类(addHasWorkorderInfoObject,...)。

这些 InfoObjects 对其“父对象”有约束,在这种情况下,“Location”有几个“LocationInfo”对象,我从数据库中检索这些对象并想将其添加到 Location。所有分配了 InfoObjects 的对象都应该发生同样的事情。

我现在正在尝试创建一种方法,该方法适用于任何遵守项目文档(位置 -> addHasLocationInfoObject,XY -> addHasXYInfoObject ...)固定命名约定的对象。

我现在向对象添加信息的方法是:

-(void)setInfoForObject:(NSManagedObject *)managedObject withClass:(NSString *)className 
NSString *noteRefName = [[NSString alloc]init];
noteRefName = [NSString stringWithFormat:@"%@Info", className];
NSString *addInfoSelectorName = [[NSString alloc]init];
addInfoSelectorName = [NSString stringWithFormat:@"addHas%@Object::", infoClassName];

SEL addInfoPropertySelector = NSSelectorFromString(addInfoSelectorName);
NSMethodSignature *signature = [[managedObject class] methodSignatureForSelector:addNotePropertySelector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];

[invocation setTarget:managedObject];
[invocation setSelector:addInfoPropertySelector];
[invocation setArgument:&note atIndex:2];

但是这给了我一个错误,因为 Signature 对象被设置为 nil。我尝试搜索问题,它似乎与选择器名称中的“:”有关。

但我不明白有多少、在哪里以及为什么我必须设置这些?我似乎也找不到告诉我如何正确执行此操作的文档页面。

感谢 Anny 的帮助,提前致谢!

附言。我记录了 SelectorName 和 Classname,它们都拼写正确。

最佳答案

好的,我发现您的代码中存在多个问题。首先,您分配空字符串实例,然后立即用新实例重写它们:

NSString *noteRefName = [[NSString alloc]init];
noteRefName = [NSString stringWithFormat:@"%@Info", className];

这是错误的。正确的做法是:

NSString *noteRefName = [NSString stringWithFormat:@"%@Info", className];

ObjC 中有两类方法:类方法和实例方法。如果您不知道其中的区别,请阅读 here .因此,第二个问题是您正在尝试使用 methodSignatureForSelector: 获取类方法签名,而不是使用 instanceMethodSignatureForSelector: 获取实例方法签名。

因此,据我所知,重写这段代码的正确方法可能是:

NSString *addInfoSelectorName = [NSString stringWithFormat:@"addHas%@Object:", infoClassName];
...
NSMethodSignature *signature = [[managedObject class] instanceMethodSignatureForSelector:addNotePropertySelector];

关于IOS NSMethodSignature 保持为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18125143/

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