gpt4 book ai didi

objective-c - 使用辅助 .h .m 文件向 NSManagedObject 添加其他属性

转载 作者:搜寻专家 更新时间:2023-10-30 19:55:17 24 4
gpt4 key购买 nike

我创建了一些 NSManagedObject 类用于 CoreData 我需要添加一些额外的属性来格式化我正在使用 GRMustache模板。

这是一个示例属性:

-(NSString *) PriceFormatted {
NSNumberFormatter *nfm = [[[NSNumberFormatter alloc] init] autorelease];
[nfm setNumberStyle:NSNumberFormatterCurrencyStyle];
[nfm setCurrencyCode:[Helpers GetCurrencyCode]];
[nfm setNegativeFormat:@"-¤#,##0.00"];
[nfm setMaximumFractionDigits:2];

return [nfm stringFromNumber:self.Price];
}

我目前在我生成的 NSManagedObject 类中有这个,但是如果我需要重新生成一个新的 NSManagedObject 类,这会导致问题。

我可以在第二组类中定义这些属性 - 类似于 C# 中的部分吗?

最佳答案

可能最简单的方法是向生成的托管对象添加类别。

Here是 Apple 的文档,这很简单。

引用:

You can add methods to a class by declaring them in an interface file under a category name and defining them in an implementation file under the same name. The category name indicates that the methods are additions to a class declared elsewhere, not a new class. You cannot, however, use a category to add additional instance variables to a class.

The methods the category adds become part of the class type. For example, methods added to the NSArray class in a category are included as methods the compiler expects an NSArray instance to have in its repertoire. Methods added to the NSArray class in a subclass, however, are not included in the NSArray type. (This matters only for statically typed objects because static typing is the only way the compiler can know an object’s class.)

Category methods can do anything that methods defined in the class proper can do. At runtime, there’s no difference. The methods the category adds to the class are inherited by all the class’s subclasses, just like other methods.

The declaration of a category interface looks very much like a class interface declaration—except the category name is listed within parentheses after the class name and the superclass isn’t mentioned. Unless its methods don’t access any instance variables of the class, the category must import the interface file for the class it extends:

    #import "ClassName.h"   

@interface ClassName ( CategoryName )
// method declarations
@end

Note that a category can’t declare additional instance variables for the class; it includes only methods. However, all instance variables within the scope of the class are also within the scope of the category. That includes all instance variables declared by the class, even ones declared @private.

There’s no limit to the number of categories that you can add to a class, but each category name must be different, and each should declare and define a different set of methods.

关于objective-c - 使用辅助 .h .m 文件向 NSManagedObject 添加其他属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9900155/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com