Objective-C

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html

Protocol的定义形式:
@protocol ProtocolName
// list of methods and properties
@end

通过属性引用一个实现了Protocol的对象:
@property (weak) id <XYZPieChartViewDataSource> dataSource;

Protocol中可以定义必须实现的方法和可选实现的方法,默认是必须实现的。使用关键字@optional和@required可以声明它们以下的方法是可选或必须实现的:
@protocol XYZPieChartViewDataSource
– (NSUInteger)numberOfSegments;
– (CGFloat)sizeOfSegmentAtIndex:(NSUInteger)segmentIndex;
@optional
– (NSString *)titleForSegmentAtIndex:(NSUInteger)segmentIndex;
– (BOOL)shouldExplodeSegmentAtIndex:(NSUInteger)segmentIndex;
@required
– (UIColor *)colorForSegmentAtIndex:(NSUInteger)segmentIndex;
@end

调用Protocol中的可选方法时需要通过respondsToSelector:和@selector()先检查对象是否实现了该方法:
NSString *thisSegmentTitle;
if ([self.dataSource respondsToSelector:@selector(titleForSegmentAtIndex:)]) {
thisSegmentTitle = [self.dataSource titleForSegmentAtIndex:index];
}

Protocol可以继承:
@protocol MyProtocol <NSObject>

@end

类实现多个协议:
@interface MyClass : NSObject <MyProtocol, AnotherProtocol, YetAnotherProtocol>

@end
注意:编译器不会合成协议中声明的属性。

Block也是OC对象,其定义形式为:
^{
NSLog(@”This is a block”);
}
^ double (double firstValue, double secondValue) {
return firstValue * secondValue;
}

同C语言里函数指针可以指向一个函数一样,OC里可以使用Block Pointer:
void (^simpleBlock)(void);

Block能抓住闭包范围内的值,但它不能改变值。如果Block要改变一个被Block抓住的变量的值,需要对该变量使用__block修饰符。
注意:Block若抓住了self时,可能引起强引用循环引用的问题。
解决循环引用的问题可以在Block内部使用__weak的self:
– (void)configureBlock {
XYZBlockKeeper * __weak weakSelf = self;
self.block = ^{
[weakSelf doSomething]; // capture the weak reference
// to avoid the reference cycle
}
}

Class中使用属性引用Block时要使用copy属性修饰符:
@interface XYZObject : NSObject
@property (copy) void (^blockProperty)(void);
@end

Operation Queues是Cocoa进行任务调度的一个途径。可以创建一个NSOperation实例将一个任务及其需要的数据封装起来,然后将它加入一个NSOperationQueue来执行。
使用NSBlockOperation创建一个使用Block的Operation:
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{

}];

// schedule task on main queue:
NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
[mainQueue addOperation:operation];

// schedule task on background queue:
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[queue addOperation:operation];

Block也可以使用Grand Central Dispatch (GCD)控制的Dispatch Queues来执行。
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(queue, ^{
NSLog(@”Block for asynchronous execution”);
});

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据