一. Category(类目) 和Extension(扩展) 文件的创建
-
command + N 打开文件模板
文件模板
-
选择 Objective-C File, 然后点击 Next
选择 Objective-C File
二. Category(类目) 和Extension(扩展)的区别
- Category(类目)
分类(类目, category),为没有源代码的类(如:NSString)扩充方法,并且只能扩充方法,不能直接扩充属性, 添加属性需要通过关联对象(Objective-C Associated Objects)
一旦添加方法,这些方法就是该类自己的方法,就可以根据具体的方法( + 号 或者 - 号方法)由类或者对象来调用
#import <Foundation/Foundation.h>
@interface NSString (SayHi)
- (void)sayHi;
+ (void)sayHello;
//添加获取首字母,不是大写,改成大写
- (NSString *)first;
//添加获取尾字母,不是小写,改成小写
- (NSString *)last;
#import "NSString+SayHi.h"
@implementation NSString (SayHi)
- (void)sayHi {
NSLog(@"hello world!");
}
+ (void)sayHello {
NSLog(@"你好");
}
//添加获取首字母,不是大写,改成大写
- (NSString *)first {
NSString *str = [[self substringToIndex:1] uppercaseString];
return str;
}
//添加获取尾字母,不是小写,改成小写
- (NSString *)last {
NSInteger length = [self length];
NSString *str = [[self substringFromIndex:length - 1] lowercaseString];
return str;
}
- Extension(扩展)
#import <Foundation/Foundation.h>
@interface Student : NSObject
{
NSString *_name;
NSString *_gender;
}
//setter
- (void)setName:(NSString *)name;
- (void)setGender:(NSString *)gender;
//getter
- (NSString *)name;
- (NSString *)gender;
#import "Student.h"
//类的延展:
//在.m 文件中, 只为有源代码的类,扩充功能(实例变量, 方法),延展中的实例变量和方法是本类私有的,只能在本类中访问.
@interface Student ()
{
NSInteger _age;
}
//sayHi
- (void)sayHi;
@end
@implementation Student
//setter
- (void)setName:(NSString *)name {
_name = name;
}
- (void)setGender:(NSString *)gender {
_gender =gender;
}
//getter
- (NSString *)name {
[self sayHi];
return _name;
}
- (NSString *)gender {
return _gender;
}
#pragma mark --- Extension Methods
//sayHi
- (void)sayHi {
NSLog(@"Hello, junyi");
}