NSDictionary 按类别添加 -objectAtIndex

发布于 2024-12-14 08:20:17 字数 1209 浏览 3 评论 0原文

我正在为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文