我一直在阅读关于NSArrays和NSDictionaires的内容,我想我需要后者。我正在尝试从小型数据库表中填充对象。所以我可以通过记录ID访问字符串值。我必须这样做几次,所以将它放入一个对象是有道理的。
我有基础......
- (void)viewDidLoad {
// WORKING START
NSMutableDictionary *dictCategories = [[NSMutableDictionary alloc] init];
[dictCategories setValue:@"Utility" forKey:@"3"];
[dictCategories setValue:@"Cash" forKey:@"5"];
NSString *result;
result = [dictCategories objectForKey:@"3"];
NSLog(@"Result=%@", result);
// WORKING END
// Can't get this bit right, current error Request for member
// 'getCategories' in something not a structure or union
NSMutableDictionary *dictCategories2 = self.getCategories;
NSLog(@"Result2=%@", [dictCategories2 objectForKey:@"5"]);
[super viewDidLoad];
}
-(NSMutableDictionary*)getCategories {
NSMutableDictionary *dictCategories = [[NSMutableDictionary alloc] init];
[dictCategories setValue:@"Utility" forKey:@"3"];
[dictCategories setValue:@"Cash" forKey:@"5"];
return dictCategories;
}
答案 0 :(得分:1)
你正在调用方法错误,请尝试[self getCategories]
答案 1 :(得分:0)
你不清楚哪些不起作用,但有些事情显然是错误的(尽管JonLOo可能会被发现)......
首先。你使用了错误的方法,或者至少有一个更好的方法 - setValue:forKey:
应该/可能是setObject:forKey:
。这可能是您遇到问题的原因之一。
其次。你过度分配而不是正确发布。 dictCategories2
中的viewDidLoad
将消失在虚空中,并带来dictCategories
方法中定义的getCategories
分配的内存。一个简单的标准修复方法是更改
NSMutableDictionary *dictCategories = [[NSMutableDictionary alloc] init];
在getCategories
进入
NSMutableDictionary *dictCategories = [NSMutableDictionary dictionary];
系统将使用后一种方法自动释放。
第三。您想阅读@property
。而不是getFoo,setBar,Ob-C标准是使用@properties来(预)定义setter和getter方法。然后,您可以覆盖这些以在适当时将默认数据填充到方法中。您(可能)也希望将字典作为实例变量存储在接口中,而不是让它一直被释放。执行此操作的@property实现示例:
@interface foo {
NSMutableDictionary *ingredients;
}
@property (nonatomic, retain) NSMutableDictionary *ingredients;
@end
// ....
@implementation foo
@synthesize ingredients;
// ...
// the @synthesize command above will create getter and setter methods for us but
// we can override them, which we need to do here
- (NSMutableDictionary *)ingredients
{
if (ingredients != nil) {
// we've already got an ingredients variable so we just return it
return ingredients;
}
// we need to create ingredients
ingredients = [[NSMutableDictionary alloc] init];
[ingredients setObject:@"foo" forKey:@"bar"]
return ingredients;
}
在viewDidLoad方法中(或您认为ingredients
可能尚未初始化的任何其他地方),您可以这样做。
NSMutableDictionary *dict = self.ingredients;
除了ingredients
之外,您可以选择仅使用self
的其他任何地方,但如果它为零,则永远不会调用您的方法,并且会向您发出nil
。
这在许多情况下很有用,如果我们想要从课堂外读取或写出成分变量,这是必要的。它超出了你所要求的范围,但我提出它是因为你试图用self.getCategories
做类似的事情。
希望有所帮助。