iOS[Block-코드를 더욱 모듈화] 장면'코드 저장','메시지 전송','파라미터 사용'[봉인 도구 클래스],'반환값'[체인 프로그래밍] 사용
1. 코드 저장
Block: 한 방법에서 정의하고 다른 방법에서 코드 장면을 호출(상용하지 않음) 저장합니다. 코드는 모델에 저장되고tableView는cell을 클릭한 상태에서 모델의 Block 코드 보기-모델-컨트롤러를 실행합니다.단계
@property (nonatomic ,strong) void(^block)();
@property (nonatomic ,strong) NSString *title;
- (void)viewDidLoad {
[super viewDidLoad];
//
CellItem *item = [[CellItem alloc] init];
item.title = @" ";
item.block = ^{
NSLog(@" ");
};
//
CellItem *item1 = [[CellItem alloc] init];
item1.title = @" ";
item1.block = ^{
NSLog(@" ");
};
//
CellItem *item2 = [[CellItem alloc] init];
item2.title = @" ";
item2.block = ^{
NSLog(@" ");
};
_cellArr = @[item,item1,item2];
}
// cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
CellItem *item = self.cellArr[indexPath.row];
if (item.block) {
item.block();
}
}
2. 메시지 전송값 [에이전트]//블록: 한 클래스에 정의되어 다른 클래스에 호출(상용)되어 -> 전송값
전송: A -> B 순전: 속성 정의 B -> A 역전: 에이전트 (block 대체 에이전트) : ,
: ,
@interface ModalViewController : UIViewController
@property (nonatomic ,strong) void(^valueBlock)(NSString *value);
@end // ,
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event //
{ if (_valueBlock) { // ,
_valueBlock(@"123");
}
}
ModalViewController *modalVc = [[ModalViewController alloc] init];
modalVc.valueBlock = ^(NSString *value){
NSLog(@" %@",value);
// ,
};
3. 매개 변수 사용 - [봉인 도구류] CalculateManager *manager = [[CalculateManager alloc]init];//
[manager calculate:^float(float result) {// /
result +=user_a_input_num;// +
result *=user_b_input_num;// *
return result; // , ,
}];
#import
@interface CalculateManager : NSObject
/** */
@property (nonatomic, assign) float result;
//
- (void)calculate:(float(^)(float result))block;
@end
#import "CalculateManager.h"
@implementation CalculateManager
- (void)calculate:(float (^)(float))block
{//
_result = block(_result);// [ ]- - [ float ]
}
@end
프로그램 실행 단계:
CalculateManager *manager = [[CalculateManager alloc]init];//
[manager calculate:^float(float result) {// /
result +=user_a_input_num;// +
result *=user_b_input_num;// *
return result; // , ,
}];
#import
@interface CalculateManager : NSObject
/** */
@property (nonatomic, assign) float result;
//
- (void)calculate:(float(^)(float result))block;
@end
#import "CalculateManager.h"
@implementation CalculateManager
- (void)calculate:(float (^)(float))block
{//
_result = block(_result);// [ ]- - [ float ]
}
@end
,
/**
* @return
*/
+ (instancetype)sharePublishedPassTime;
/** - passTimes_str */
@property (nonatomic, strong) NSString *passTimes_str;
/**
* [passTimes_str= - ]
*
* @param str_time
* @param passTimes_str
*
* @return
*/
- (NSString *)PublishedPassTimeWithTimeNSString:(NSString *)str_time result:(void(^)(NSString *passTimes_str))passTimes_str;
- (NSString *)PublishedPassTimeWithTimeNSString:(NSString *)str_time result:(void(^)(NSString *passTimes_str))passTimes_str
{
// [ ]
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm";
// @"yyyy-MM-dd HH:mm:ss Z"; @"2015-06-29 07:05:26 +0000";
NSDate *date = [formatter dateFromString:str_time];
//
NSDate *now = [NSDate date];
/** */
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit type = NSCalendarUnitYear |
NSCalendarUnitMonth |
NSCalendarUnitDay |
NSCalendarUnitHour |
NSCalendarUnitMinute |
NSCalendarUnitSecond;
NSDateComponents *cmps = [calendar components:type fromDate:date toDate:now options:0];
if (cmps.year != 0) {
_passTimes_str = [NSString stringWithFormat:@"%ld ",cmps.year];
}else if (cmps.month != 0){
_passTimes_str = [NSString stringWithFormat:@"%ld ",cmps.month];
}else if (cmps.day != 0){
_passTimes_str = [NSString stringWithFormat:@"%ld ",cmps.day];
}else if (cmps.hour != 0){
_passTimes_str = [NSString stringWithFormat:@"%ld ",cmps.hour];
}else if (cmps.hour != 0){
_passTimes_str = [NSString stringWithFormat:@"%ld ",cmps.minute];
}else{
_passTimes_str = @" ";
}
passTimes_str(_passTimes_str);
return _passTimes_str;
}
[[GLPublishedPassTime sharePublishedPassTime] PublishedPassTimeWithTimeNSString:item.create result:^(NSString *passTimes_str) {// cell set
self.create.text = passTimes_str;
}];
static GLPublishedPassTime *_instance;
/** */
+ (instancetype)sharePublishedPassTime
{
return [[self alloc]init];
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
@synchronized(self) {
if (_instance == nil) {
_instance = [super allocWithZone:zone];
}
}
return _instance;
}
프로그램 실행 단계:
4. 반환값[체인 프로그래밍]
수요: 외부에서 계산 매개 변수만 전달하고 점 문법[속성 값 획득]을 사용하거나 [계산 수정 어떤 속성]을 사용하며 계산은 도구 클래스에 봉인됩니다.외부에서 어떻게 사용하고, 내부 공구를 어떻게 설계하는가.CalculateManager *mgr = [[CalculateManager alloc]init];
NSLog(@"%d",mgr.add(5).add(5).add(5).result);
#import
@interface CalculateManager : NSObject
/** result */
@property (nonatomic, assign) int result;
- (CalculateManager *(^)(int value))add;
@end
#import "CalculateManager.h"
@implementation CalculateManager
-(CalculateManager *(^)(int))add
{
return ^(int value){
_result +=value;
return self;
};
}
@end
봉인 도구 클래스: 반환값에 Block을 정의하고 Block에 문자열 파라미터를 입력하며 계산 결과는 도구 클래스 속성에 저장합니다self.create.text = [GLPublishedPassTime sharePublishedPassTime].passTime(item.create).passTimes_str;
/** - passTimes_str */
@property (nonatomic, strong) NSString *passTimes_str;
/**
* block str_time , passTimes_str
*/
- (GLPublishedPassTime *(^)(NSString *str_time))passTime;
- (GLPublishedPassTime *(^)(NSString *))passTime
{
return ^(NSString *str_time){
// [ ]
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm";
// @"yyyy-MM-dd HH:mm:ss Z"; @"2015-06-29 07:05:26 +0000";
NSDate *date = [formatter dateFromString:str_time];
//
NSDate *now = [NSDate date];
/** */
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit type = NSCalendarUnitYear |
NSCalendarUnitMonth |
NSCalendarUnitDay |
NSCalendarUnitHour |
NSCalendarUnitMinute |
NSCalendarUnitSecond;
NSDateComponents *cmps = [calendar components:type fromDate:date toDate:now options:0];
if (cmps.year != 0) {
_passTimes_str = [NSString stringWithFormat:@"%ld ",cmps.year];
}else if (cmps.month != 0){
_passTimes_str = [NSString stringWithFormat:@"%ld ",cmps.month];
}else if (cmps.day != 0){
_passTimes_str = [NSString stringWithFormat:@"%ld ",cmps.day];
}else if (cmps.hour != 0){
_passTimes_str = [NSString stringWithFormat:@"%ld ",cmps.hour];
}else if (cmps.hour != 0){
_passTimes_str = [NSString stringWithFormat:@"%ld ",cmps.minute];
}else{
_passTimes_str = @" ";
}
return self;
};
}
/** */
+ (instancetype)sharePublishedPassTime
{
return [[self alloc]init];
}
마지막으로 요약: Block이 개발에서 가장 긴 것은 두 번째입니다
.세 번째와 네 번째 사용 장면에 대해 처리해야 할 방법으로 많이 사용한다.위와 같이 되돌아오는 값이 필요할 뿐입니다. 사용자 정의 도구 클래스 중 하나의 클래스 방법으로 해결할 수 있습니다.
마지막으로 모두 건강하세요.안녕히 계십시오.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSON
JSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다.
그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다.
저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.
CalculateManager *mgr = [[CalculateManager alloc]init];
NSLog(@"%d",mgr.add(5).add(5).add(5).result);
#import
@interface CalculateManager : NSObject
/** result */
@property (nonatomic, assign) int result;
- (CalculateManager *(^)(int value))add;
@end
#import "CalculateManager.h"
@implementation CalculateManager
-(CalculateManager *(^)(int))add
{
return ^(int value){
_result +=value;
return self;
};
}
@end
self.create.text = [GLPublishedPassTime sharePublishedPassTime].passTime(item.create).passTimes_str;
/** - passTimes_str */
@property (nonatomic, strong) NSString *passTimes_str;
/**
* block str_time , passTimes_str
*/
- (GLPublishedPassTime *(^)(NSString *str_time))passTime;
- (GLPublishedPassTime *(^)(NSString *))passTime
{
return ^(NSString *str_time){
// [ ]
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm";
// @"yyyy-MM-dd HH:mm:ss Z"; @"2015-06-29 07:05:26 +0000";
NSDate *date = [formatter dateFromString:str_time];
//
NSDate *now = [NSDate date];
/** */
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit type = NSCalendarUnitYear |
NSCalendarUnitMonth |
NSCalendarUnitDay |
NSCalendarUnitHour |
NSCalendarUnitMinute |
NSCalendarUnitSecond;
NSDateComponents *cmps = [calendar components:type fromDate:date toDate:now options:0];
if (cmps.year != 0) {
_passTimes_str = [NSString stringWithFormat:@"%ld ",cmps.year];
}else if (cmps.month != 0){
_passTimes_str = [NSString stringWithFormat:@"%ld ",cmps.month];
}else if (cmps.day != 0){
_passTimes_str = [NSString stringWithFormat:@"%ld ",cmps.day];
}else if (cmps.hour != 0){
_passTimes_str = [NSString stringWithFormat:@"%ld ",cmps.hour];
}else if (cmps.hour != 0){
_passTimes_str = [NSString stringWithFormat:@"%ld ",cmps.minute];
}else{
_passTimes_str = @" ";
}
return self;
};
}
/** */
+ (instancetype)sharePublishedPassTime
{
return [[self alloc]init];
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.