Masonry等第三方库采用链式调用方式,使用时够简单、惊艳。下面来模仿一下,分析就省略了,so直接看代码。
1.Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject
- (Person *(^)(NSString *))name;
- (Person *(^)(NSString *))address;
@end
2.Person.m
#import "Person.h"
@interface Person ()
{
NSString *_name;
NSString *_address;
}
@end
@implementation Person
- (Person *(^)(NSString *))name {
return ^Person *(NSString *name){
NSLog(@"%@--%@", NSStringFromSelector(_cmd), name);
_name = name;
return self;
};
}
- (Person *(^)(NSString *))address {
return ^Person *(NSString *address){
NSLog(@"%@--%@", NSStringFromSelector(_cmd), address);
_address = address;
return self;
};
}
- (NSString *)description {
return [NSString stringWithFormat:@"{name:%@,address:%@}", _name, _address];
}
@end
3.main.m
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *person = [Person new];
person.name(@"Jack").address(@"USA");
NSLog(@"person = %@", person);
}
return 0;
}