【问题标题】:NSMutableDictionary setObject:forKey - custom classNSMutableDictionary setObject:forKey - 自定义类
【发布时间】:2011-10-21 15:59:17
【问题描述】:

我在 UINavigation 环境中使用它。 我有 customClassA。它继承了 customClassB,其中一个对象是 NSMutableDictionary。

我在 viewController 中分配和初始化 customClassA,然后为了添加数据,我将新的 viewController 推入堆栈。 addNewDataViewController 发送新添加的数据,一个 customClassB 对象由它的委托返回。到目前为止一切正常。

customClassA 必须使用键(从 NSDate 创建的 NSString)将返回的对象 (customClassB) 存储到其 NSMutableDictionary 对象中。

我收到“发送到不可变对象的变异方法”错误,想不出任何解决方案。 任何帮助表示赞赏。

谢谢。

============================

interface customClassA : NSObject
{
    NSDate date;
    NSArray *array; // will contain only NSString objects
}
// and the rest as customary
...

#import "customClassA.h"
interface customClassB : NSObject
{
    NSString *title;
    NSMutableDictionary *data; // will contain values of customClassA with keys of NSString
}
// and the rest as customary

...

#import "customClassB"
#interface firstViewController : UITableViewController <SecondViewControllerDelegate>
- (void)viewDidLoad
{
      self.customClassB_Object = [customClassB alloc] init];
      //  and the rest...
}

- (void)secondViewControllerDidSaveData:(customClassA *)aData
{
    [self.customClassB_Object.data setObject:aData forKey:[NSString stringWithFormat:@"%@", aData.date]];
    // update tableView
}

【问题讨论】:

  • 您能否围绕问题区域发布更多代码以及如何创建 NSMutableDictionary
  • 我发布了一些代码。希望对您有所帮助。
  • customClassB_Object 定义在哪里?
  • self.customClassB_Object 在头文件中定义并在 viewDidLoad 中分配、初始化。
  • 你需要在 secondViewControllerDidSaveData 中做 self.customClassB_Object.data

标签: cocoa nsmutabledictionary


【解决方案1】:

确保您使用类似的东西初始化NSMutableDictionary

NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] init];

您的NSMutableDictionary 似乎是使用NSDictionary 实例而不是NSMutableDictionary 创建的

【讨论】:

  • 已经做到了。没用。事实上,手动给它一个对象和一个键,当 addNewDataViewController 弹出时,它仍然持有那个手动输入的对象。但拒绝 setObject:forKey !!!
  • 您需要发布更多代码。围绕问题区域设置断点/记录日志可能会有所帮助。
【解决方案2】:

虽然我在 customClassB 实现中添加了以下代码,但它仍然不起作用。

#implementation customClassB
- (id)init
{
      self = [super init];
      if (self)
          self.data = [NSMutableDictionary alloc] init];
      return self;
}

所以我在我的 customClassB 实现以及头文件中添加了两个自定义方法:

- (void)appendData:(customClassA *)aData;
- (void)removeDataWithKey:(NSString *)aKey;

我没有在 viewController 中操作 customClassB 的数据字典,而是调用该方法并将数据对象传递给类,它就成功了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    • 2023-03-13
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多