I have a dictionary that I read from a plist. I want to create a subclass of NSDictionary
to implement something like the following, so that I can avoid using @"key name"
everywhere in my source code:
@interface MyDict{
}
-(NSString*) textString;
@end
@implementation MyDict
-(NSString*) textString {
return [self objectForKey:@"textString"];
}
@end
In my other method:
MyDict *d = ... // something i read from plist
NSString *str = [d textString];
When I call the method, the app crashes because of "unrecognized selector textString". What is wrong here?
Just assigning an NSDictionary to a MyDict pointer doesn't make it a MyDict instance.
One way you can do this would be to create a category to add your method to NSDictionary. See http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocCategories.html#//apple_ref/doc/uid/TP30001163-CH20-SW1 for info.
Your class has no superclass. Also, the conventional wisdom is that it's very difficult to subclass NSDictionary
because it is an class cluster . You don't actually get an NSDictionary
back when you:
NSDictionary * myDict = [NSDictionary dictionary];
You get a private subclass ( NSCFDictionary
in this case).
You might want to try defining your own dictionary keys, the way Apple does:
NSString * const MyWonderfulUnicornKey = @"MyWonderfulUnicornKey";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.