NSMutableDictionary 条目在离开添加条目的方法后损坏

NSMutableDictionary entry corrupted after departing from the method where entry was added

我使用 setObject:forKey: 将类型为 Rresource 的对象添加到名为:resourceLib 的 NSMutableDictionary。

那我立马看看字典里到底是什么,还行

当我尝试在另一个对象的方法中再次查看它时,出现了正确的键,但对字符串的引用 属性 "url" 导致错误消息列表,包括:

2016-09-28 11:32:42.636 testa[760:16697] -[__NSCFString url]: 无法识别的选择器发送到实例 0x600000456350

Rresource 对象定义为:

@interface Rresource : NSObject
@property (nonatomic,strong) NSString* url;
@property (nonatomic,strong)NSMutableArray* resourceNotesArray;
@property(nonatomic,strong)NSString* name;
@property(nonatomic,strong)NSString* resourceUniqueID;
@property(nonatomic)BOOL isResourceDirty;

此方法在 ViewController 中将 RResource 添加到 NSMutableDictionary

-(void)saveResource
{
Rresource* resource = self.currentResource;
Rresource* temp;
if (resource)
{
    if ( resource.isResourceDirty)
    {
        [self.model.resourceLib setObject:resource forKey:resource.resourceUniqueID];
        temp = [self.model.resourceLib objectForKey:resource.resourceUniqueID];
    }
}

}

资源和临时文件包含相同的信息,表明信息已正确添加。

在模型的方法中,以下导致上述错误消息。

for (Rresource* resource in self.resourceLib)
{
    NSString* string = resource.url;
}

其中模型包含:

@property(nonatomic,strong)NSMutableDictionary* resourceLib;

和:

@implementation Model


- (instancetype)init
{
self = [super init];
if (self)
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    self.path = [[paths objectAtIndex:0] stringByAppendingString:@"/Application Support/E2"];
    BOOL exists = [[NSFileManager defaultManager] createDirectoryAtPath:self.path withIntermediateDirectories:NO attributes:nil error:nil];
    if (!exists)
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:self.path withIntermediateDirectories:NO attributes:nil error:nil];
    }
    self.resourceLibPath = [NSString pathWithComponents:@[self.path,@"resources"]];
    self.resourceLib = [[NSMutableDictionary alloc]init];
    self.noteLibPath = [NSString pathWithComponents:@[self.path, @"notes"]];
    self.noteLib = [[NSMutableDictionary alloc]init];
}
return self;

我发现这个问题即使花了几个小时来表述也很难问清楚。我道歉。

我已经尝试了大约一个星期的几乎所有方法。我被难住了。

有什么想法吗?

谢谢

根据 this entry on Enumeration,当您使用快速枚举语法遍历字典时,您就是在遍历它的键。在上面的代码示例中,您假设枚举发生在它的值上。您有效地做的是将 NSString 对象转换为 Rresource,并向它发送一个只有实际 Rresource 对象可以响应的选择器。

这应该可以修复循环:

for (NSString* key in self.resourceLib)
{
    NSString* string = [self.resourceLib objectForKey:key].url;
}