Ios 添加到超类';子类中的s结构

Ios 添加到超类';子类中的s结构,ios,objective-c,mogenerator,Ios,Objective C,Mogenerator,我正在使用Mogenerator为我的CoreData构建类,我喜欢它基于CoreData属性生成的属性名称,如\u TAGUser的头文件中所示: extern const struct TAGUserAttributes { __unsafe_unretained NSString *displayName; __unsafe_unretained NSString *email; } TAGUserAttributes; @interface _TAGUser : NSM

我正在使用Mogenerator为我的CoreData构建类,我喜欢它基于CoreData属性生成的属性名称,如
\u TAGUser
的头文件中所示:

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
@implementation TAGUser

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

@end
现在在子类
TAGUser
中,我将此属性添加到头文件中:

@interface TAGUser : _TAGUser {}

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

@end
并将其添加到实现文件中:

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

@implementation _TAGUser

@end
@implementation TAGUser

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

@end

是否有一种方法可以扩展或添加到结构
TAGUserAttributes
,以便在代码中的任何其他地方调用
TAGUserAttributes。对于KVO,firstLetterOfDisplayName
NSFetchedResultsController
中的节映射等?

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

  • 对KVO等使用
    NSStringFromSelector(显示名的第一个字母)
    。这样可以获得一些编译器安全性。如果给定名称的选择器不存在,编译器将进行投诉。但是,选择器可以存在于可见范围内的任何位置,而不仅仅存在于
    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

不幸的是,指针语法使它非常难看,但它仍然可以工作。

您不必检查:
self.displayName!=无
。在发送到
nil
的Objective-C消息中,返回0,因此如果
self.displayName
nil
,则
self.displayName.length
将为0。是的,我认为不能仅仅扩展C结构,因为它不是面向对象的,但这些都是有意义的。也许我会做你的第二个建议,或者做一个属性或方法,它是
NSStringFromSelector(firstLetterOfDisplayName)
的包装器。我会把这个问题留待几天,看看是否有其他建议通过,否则我会接受答案。谢谢