所以我试图将数组保存到NSDictionary中。让我告诉你代码并解释发生了什么。
for (int x= 0; x <[appDelegate.people count]; x++) {
Person *aPerson = [[Person alloc] init];
aPerson = [appDelegate.people objectAtIndex:x];
if ([appDelegate.groupedBusiness objectForKey:aPerson.business_name] == nil) {
NSMutableArray *newBusiness = [[NSMutableArray alloc] init];
//if the business does not exist in the dict, add the person to the business and add it to dict.
[newBusiness addObject:aPerson];
[appDelegate.groupedBusiness setObject:newBusiness forKey:aPerson.business_name];
[newBusiness release];
newBusiness = nil;
//NSLog(@"%@", appDelegate.groupedBusiness);
} else {
NSMutableArray *existingBusiness= [appDelegate.groupedBusiness objectForKey:aPerson.business_name];
[existingBusiness addObject:aPerson];
//THIS IS THE LINE I AM NOT SURE ABOUT!!!
[appDelegate.groupedBusiness setObject:existingBusiness forKey:aPerson.business_name];
[existingBusiness release];
existingBusiness = nil;
//NSLog(@"%@", appDelegate.groupedBusiness);
}
}
好吧,所以appDelegate有一个“People”数组,它有一大堆关于一个人的属性。我正在尝试设置一个字典,按照他们的商家名称对它们进行排序。我这样做是通过创建一个数组并将其保存在字典中,并将business_name作为键。我检查循环的每次迭代以查看密钥是否存在,如果存在,拉出现有数组,添加要检查的人,并将其重新保存到字典中。但是,这似乎并没有发生。在NSDictionary类中是否存在一些可以防止这种情况的异国行为?我已经倾倒了课程网页,找不到任何东西。对不起,如果这是一个noobie问题,我仍然试图理解objective-c类。谢谢!
答案 0 :(得分:2)
为什么要发布现有业务?您不是创建一个对象,只是从数组中获取指针。当您调用release时,retainCount变为0并且对象deallocs。
只需删除以下两行:
[existingBusiness release];
existingBusiness = nil;
一切都应该正常。
答案 1 :(得分:2)
你太过于复杂了,更不用说泄漏一些东西了。
for (Person *aPerson in appDelegate.people) {
NSMutableArray *business = [appDelegate.groupedBusiness objectForKey:aPerson.business_name];
if (!business) {
business = [NSMutableArray array];
[appDelegate.groupedBusiness setObject:business forKey:aPerson.business_name];
}
[business addObject:aPerson];
}
答案 2 :(得分:1)
不是答案,而是一些编码风格问题。
如果您不需要索引,请使用快速迭代:
for (Person *aPerson in appDelegate.people) {
使用便利构造函数;它使你的代码更具可读性(记得在最后删除“发布”):
NSMutableArray *newBusiness = [NSMutableArray arrayWithObject:aPerson];
尽可能避免重复逻辑:
NSMutableArray * business = [appDelegate.groupedBusiness objectForKey:aPerson.business_name;
if (!business) {
business = [NSMutableArray array];
}
[business addObject:aPerson];
[appDelegate.groupedBusiness setObject:business forKey:aPerson.business_name];
除了浪费CPU周期之外,“setObject:existingBusiness”调用确实没有任何改变,但在上面的例子中,它使代码更具可读性。
答案 3 :(得分:0)
[appDelegate.groupedBusiness setObject:existingBusiness forKey:aPerson.business_name];
[existingBusiness release];
existingBusiness = nil;
这一切都应该删除。 existingBusiness已经在dict中了,它是一个可变对象 - 当你向它添加一个人时,这将反映在字典中,并且它与你正在处理的对象相同。除此之外,丹尼尔指出,你有几个内存泄漏。