iOS category中的所谓属性 和 从xib初始化对象的方法 以及类扩展

今天在编码时遇到以下代码

@interface UITextField (TCCustomFont)
@property (nonatomic, copy) NSString* fontName;
@end

@implementation UITextField (TCCustomFont)

- (NSString *)fontName {
    return self.font.fontName;
}

- (void)setFontName:(NSString *)fontName {
    self.font = [UIFont fontWithName:fontName size:self.font.pointSize];
}

@end

在学习oc开始阶段就学过:类别不能像类中加成员变量,那么这个 fontName是不是违反了这个规则呢?

其实没有! @property 的作用就是声明方法,与成员变量无关,当你写了@property (nonatomic, copy) NSString* fontName; 系统会自动把它翻译成- (NSString *)fontName 和- (void)setFontName:(NSString *)fontName 2个方法,并没有指定这2个方法的实现。只有你用了系统的@synthesize 来实现get 和set方法,系统才会自动为你建立与之相应的类成员变量,但是,如果你自己实现了自己的 get 和set的方法,那么这2个操作就和成员变量无关了,所以说类别还是无法向原来的类中添加成员变量的。比如上面的代码,get 和 set 的操作都和fontName类成员变量无关!所以,这样写仅仅是一种简单声明的方法。另外需要注意,xcode4.5版本如果你不写@synthesize 编译器会为你自动添加的,所以想实现自己的方法一定要重写get和set方法。

 

利用这这种特性,可以实现另一种初始化xib的方法,比如我想在ViewController类从xib初始化时调用nslog出入一段文字,那么可以在ViewController中添加如下代码

- (void)setFontName:(NSString *)fontName {
    NSLog(@"........");
}

之后,在xib中设置,如下图

请注意右边的user defined runtime attributes .这样就达到了目的!从xib编辑器看,这个设定好像是设定了对象的属性,但是我们仅仅是想借此调用一个自己的初始化函数而已。

另外,需要提一下类似于category的特性,class extension

class extension 就是以下写法

@interface MasterViewController ()
- (void)updateTableContents;
- (void)sortByValue;
@end

这种class extension和普通的category有什么区别呢?

So how is this different from a regular category? First, the compiler will check to make sure that these methods are actually implemented in the @implementation section of the class (and throw a warning otherwise) – something it doesn’t do for categories. Second, you can declare properties inside a class extension.Besides properties, it is also possible to put instance variables in the class extension. 

简单的来说,就是class extension可以含有成员变量。比如:

@interface ViewController ()
{
    NSString * testName;
}

@property (strong,nonatomic) NSString *name2;

@end

这里testName就是新加入的成员变量。

 

 

posted @ 2014-01-28 10:11  幻化成疯  阅读(944)  评论(0编辑  收藏  举报