NSDictionary 按类别添加 -objectAtIndex
我正在为 Quartz Composer 编写自定义补丁,并使用结构作为输入。 Obj-C 中的结构体是 NSDictionary,所以我使用 NSDictionary 的方法来处理这些结构体。根据我构建这些结构的方式,键可以是 NSString 类型或 NSNumber。
通常QC不会给出命名结构,键是“0”...“n”或0...n,所以我决定在 NSDictionary 类别中添加 -objectAtIndex :
NSDictionary+Utils.h
#import <Foundation/Foundation.h>
@interface NSDictionary (Utils)
- (id)objectAtIndex:(NSInteger)index;
@end
NSDictionary+Utils.m
#import "NSDictionary+Utils.h"
@implementation NSDictionary (Utils)
- (id)objectAtIndex:(NSInteger)index
{
NSString* key = [NSString stringWithFormat:@"%d", index];
return [self objectForKey:key];
}
@end
它非常适合我的一个项目,在该项目中我使用 Kineme Struc Maker 补丁构建了一个结构。 在另一个项目中我使用苹果提供的队列补丁。键不是 NSString 类型,而是 NSNumber 类型。我重写了代码以符合 NSNumber 键:
NSDictionary+Utils.m
@implementation NSDictionary (Utils)
- (id)objectAtIndex:(NSInteger)index
{
NSNumber* key = [NSNumber numberWithInteger:index];
return [self objectForKey:key];
}
@end
不幸的是,它总是给出空值,但使用:
[self.inputSoundStruct objectForKey:[NSNumber numberWithInteger:0]]
为什么这行代码有效,但 objectAtIndex 无效?我一定是错过了什么,但是什么?
I'm writing custom patch for Quartz Composer and I work with structures as input. Structure are NSDictionary in Obj-C so I use NSDictionary's methods to deal with these structures. Depending on how I build these structures key can be NSString type or NSNumber.
Usually QC doesn't give named structures and keys are "0"..."n" or 0...n so I've decided to add -objectAtIndex in a NSDictionary category :
NSDictionary+Utils.h
#import <Foundation/Foundation.h>
@interface NSDictionary (Utils)
- (id)objectAtIndex:(NSInteger)index;
@end
NSDictionary+Utils.m
#import "NSDictionary+Utils.h"
@implementation NSDictionary (Utils)
- (id)objectAtIndex:(NSInteger)index
{
NSString* key = [NSString stringWithFormat:@"%d", index];
return [self objectForKey:key];
}
@end
It works perfectly for one of my project in which I build a structure using Kineme Struc Maker patch.
In another project I use the Queue patch provided by apple. Keys are not NSString type but NSNumber type. I've rewritten the code to be compliant with NSNumber keys :
NSDictionary+Utils.m
@implementation NSDictionary (Utils)
- (id)objectAtIndex:(NSInteger)index
{
NSNumber* key = [NSNumber numberWithInteger:index];
return [self objectForKey:key];
}
@end
Unfortunately it always gives a null value but using :
[self.inputSoundStruct objectForKey:[NSNumber numberWithInteger:0]]
Why does this line of code works but not objectAtIndex ? I must be missing something but what ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论