1. 类目(Category)
为原始的类添加新的方法来简便使用,例如:对 NSString 添加去除前后空格的 快捷方法
#import <Foundation/Foundation.h>
@interface NSString (Help)
/**
* 去空白
*
*/
- (NSString *)trimString;
@end
#import "NSString+Help.h"
@implementation NSString (Help)
- (NSString *)trimString
{
//去除字符串 2端的空格
return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
@end
2. 延展(Extension)
定义自己的私有方法和属性,不能和外界共用
#import <UIKit/UIKit.h>
@class MKButton;
@interface ViewController : UIViewController
@end
@interface MKButton : UIButton
@property (assign, nonatomic) NSInteger flag;// 新属性
- (void)text; //新方法
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
MKButton * mk = [[MKButton alloc]initWithFrame:CGRectMake(100, 100, 100, 50)];
mk.tag = 1;
mk.flag = 105;
mk.backgroundColor = [UIColor blueColor];
[mk addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:mk];
}
- (void)click:(MKButton *)btn
{
NSLog(@"%ld",btn.tag);
NSLog(@"%ld",btn.flag);
[self text];
}
- (void)text
{
NSLog(@"您调用了私有方法");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
@implementation MKButton
- (void)text
{
}
@end
3.协议(Protocol)
讲的是传值的作用和方法的调用,要用到两个文件名
#import <UIKit/UIKit.h>
@protocol SimpleProtocol <NSObject>
@required //必须遵守的协议[若不写 则是必须遵守的协议]
- (void)mustRealize:(NSString *)value;
@optional //可选的协议
- (void)maybeRealize:(NSString *)value;
@end
@interface SimpleView : UIView
@property (weak, nonatomic) id<SimpleProtocol>delegate;
- (void)chooseDelegate;
@end
#import "SimpleView.h"
@implementation SimpleView
- (instancetype)initWithFrame:(CGRect)frame
{
if ([super initWithFrame:frame]) {
}
return self;
}
- (void)chooseDelegate
{
if (self.delegate && [self.delegate respondsToSelector:@selector(maybeRealize:)]) {
[self.delegate maybeRealize:@"可选协议传值"];
}
if (self.delegate && [self.delegate respondsToSelector:@selector(mustRealize:)]) {
[self.delegate mustRealize:@"必选协议传值"];
}
}
@end
应用:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
#import "ViewController.h"
#import "SimpleView.h"
@interface ViewController ()<SimpleProtocol>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
SimpleView *simple = [[SimpleView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
simple.backgroundColor = [UIColor redColor];
simple.delegate = self;
[simple chooseDelegate];
[self.view addSubview:simple];
}
- (void)maybeRealize:(NSString *)value
{
NSLog(@"%@",value);
}
- (void)mustRealize:(NSString *)value
{
NSLog(@"%@",value);//必选协议传值 若是不写会有警告
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end