1

更新:现在工作(按照建议添加了修复 - 谢谢!)

我一直在尝试克隆NSDictionary员工信息。mainNSDictionary在不同的类中创建并在prepareForSegue. 我希望能够NSDictionary在另一个类中创建一个可变副本,然后可以更新员工信息并将其发送到另一个类进行处理,这样我以后仍然可以使用原始未更改的数据集。我在 Stack 上找到了一些不同的示例,但没有什么可以开始工作。当我在调用后中断btn_click方法并检查本地pp对象时,仍然为零。我在这里做错了什么?..objectForKeypp

obj_person.h

#import <Foundation/Foundation.h>

@interface obj_person : NSObject
@property (strong,nonatomic)  NSString *personID;
@property (strong, nonatomic) NSString *personName;
@property (strong, nonatomic) NSString *personTitle;
@end

obj_person.m

#import "obj_person.h"

@implementation obj_person
@synthesize personID = _personID;
@synthesize personName = _personName;
@synthesize personTitle = _personTitle;

@结尾

视图控制器.m

#import "ViewController.h"
#import "obj_person.h"

@interface ViewController ()

@end

@implementation ViewController

int mCounter = 1;
NSMutableDictionary *mCopy;
NSMutableDictionary *mNsd;

- (void)viewDidLoad
{
   [super viewDidLoad];

   NSArray *arnames = [[NSArray alloc] initWithObjects:@"mary", @"jane", @"stan", @"cartman", nil];
   NSArray *arkeys = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2],[NSNumber numberWithInt:3], [NSNumber numberWithInt:4], nil];
   mNsd = [[NSMutableDictionary alloc] initWithCapacity:[arnames count]];

   int i = 0;
   for (NSString *name in arnames)
   {
      obj_person *p = [[obj_person alloc] init];
      p.personID = [arkeys objectAtIndex:i];
      p.personName = name;

      [mNsd setObject:p forKey:p.personID];
      i++;
   }

   mCopy = [mNsd mutableCopy];
}

- (IBAction)btn_click:(id)sender
{
   NSLog (@"%d original items", [mNsd count]);
   obj_person *pp = [mCopy objectForKey:[NSNumber numberWithInt:mCounter]];
   NSLog(@"%@", pp.personName);
   pp.personName = @"Gerald";

   if (++mCounter > [mCopy count])
      mCounter = 1;
}

@end
4

2 回答 2

3

Don't define:

NSMutableDictionary *mCopy;
NSMutableDictionary *mNsd;

Outside of the @interface and @implementation. They should be instance variables, so define instance variables or use properties to define them.

It's a good job you don't use n from:

for (NSArray *n in arnames)

because it isn't an NSArray, it's an NSString. You should fix that and you should probably both name it better than n and use it.

This:

obj_person *pp = [mCopy objectForKey:[NSNumber numberWithInt:1]];

fails because the key you originally stored with is an NSString instance and the thing you are using to try to get the data out is an NSNumber instance (so they can never match).

于 2013-10-15T17:58:29.263 回答
0

你可以试试:

mCopy = [mNsd mutableCopy];
[mCopy retain]

一种理论是 mutableCopy 返回的是一个自动释放的对象,它在 btn_click 函数触发之前被杀死。根据这篇文章:Retain/release of returned objects, mutableCopy 不应该自动释放数组,但确实会发生错误。

否则,也许可以尝试使用 for 循环进行迭代。

int cnt = [arnames count];
for(int i=0; i<cnt; i++) 
...
于 2013-10-15T18:03:28.380 回答