ios - 在子类中添加到父类(super class)的结构

标签 ios objective-c mogenerator

我正在使用 Mogenerator 为我的 CoreData 构建类,我喜欢它根据 _TAGUser 的头文件中的 CoreData 属性生成的属性名称:

extern const struct TAGUserAttributes {
    __unsafe_unretained NSString *displayName;
    __unsafe_unretained NSString *email;
} TAGUserAttributes;

@interface _TAGUser : NSManagedObject

@property (nonatomic, strong) NSString* displayName;
@property (nonatomic, strong) NSString* email;

@end

在实现文件中:

const struct TAGUserAttributes TAGUserAttributes = {
    .displayName = @"displayName",
    .email = @"email",
};

@implementation _TAGUser

@end

现在在子类 TAGUser 中,我将这个属性添加到头文件中:

@interface TAGUser : _TAGUser {}

@property (strong, nonatomic, readonly) NSString *firstLetterOfDisplayName;

@end

这是实现文件:

@implementation TAGUser

- (NSString *)firstLetterOfDisplayName {
    return ((self.displayName != nil && self.displayName.length > 0) ?
        [self.displayName substringToIndex:1].uppercaseString :
        nil);
}

@end

有没有一种方法可以扩展或添加到结构 TAGUserAttributes 以便我可以在代码中的任何其他地方调用 TAGUserAttributes.firstLetterOfDisplayName 以获取 KVO、部分映射在 NSFetchedResultsController 等中?

最佳答案

不能简单地扩展 C 结构。您有两种可能的方法:

  • 对 KVO 等使用 NSStringFromSelector(firstLetterOfDisplayName)。这样您可以获得一些编译器安全性。如果具有给定名称的选择器不存在,编译器将报错。但是,选择器可以存在于可见范围内的任何位置,而不仅仅是在您的 TagUser 类中,以使编译器满意。

  • 我在这里和那里看到的另一种方法是添加另一个结构,其中包含指向原始结构的指针。我现在想不出更好的命名方式,但我希望它能被理解:

在 .h 文件中:

extern const struct TAGUserAdditionalAttributes {
    const struct TAGUserAttributes* base;
    __unsafe_unretained NSString * firstLetterOfDisplayName;
} TAGUserAdditionalAttributes;

在 .m 文件中:

const struct TAGUserAdditionalAttributes TAGUserAdditionalAttributes = {
    .base = &TAGUserAttributes,
    .firstLetterOfDisplayName = @"firstLetterOfDisplayName"
};

   //then you can use "base" attributes like this:
   TAGUserAdditionalAttributes.base->displayName

不幸的是,指针语法使它变得很丑陋,但它仍然有效。

关于ios - 在子类中添加到父类(super class)的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27929068/

相关文章:

ios - 如何从名称中带点的 cocoapods 导入库?

ios - 如何只为一个类启用底部导航栏

sqlite - 使用python创建的sqlite-shm和sqlite-wal文件从json生成sqlite

core-data - Mogenerator - 构建时不生成文件

iPhone 应用程序 : how to implement Google Places Api

ios - 发电机 ios

ios - 音频硬件.cpp :1200:AudioObjectRemovePropertyListener: AudioObjectRemovePropertyListener: no object with given ID 0

audio - 音频工具箱播放mp3文件(iOS)

ios - 图像尺寸太大时 Tableview 单元格抖动

ios - 如何从我的 iPad 应用程序 (Objective-C) 打开设置