现在的位置: 首页 > 综合 > 正文

Objective-C的blocks语法

2013年07月09日 ⁄ 综合 ⁄ 共 2134字 ⁄ 字号 评论关闭

OC中的blocks和C++中的函数指针类似,从外观和使用上可以看出

Int(*CFunc)(int a);   //C语言的函数指针。 调用   Intret=(CFunc)(10);

Int(^BFunc)(int a);   //Blocks                        
调用         intret=(BFunc)(10);

也可以使用typedef关键字来定义blocks

typedef (void)(^BFunc)(int a,int b);

BFunc func=^(int a,int b){

return a+b;

};

func(10,20);即可调用block块。

__blocks关键字

如下代码:

typedef (void)(^BFunc)(int a,int b);
__blocks int sum;
BFunc func=^(int a,int b){
	sum=a+b;
        return sum;
};

如果没有__blocks关键字修饰 sum,那么在blocks块中,sum就会提示错误,没有定义

苹果官方建议尽量多用blocks应用。在多线程,异步任务,动画转场用的很多,用在回调时候,可以使用这种机制。

考虑如下情景:

一个Person类,一个Dog类,每个Person有一个Dog,当dog发先情况时候,会通知主人,也就是调用主人的方法。通过协议可以实现,这里使用blocks回调机制来实现:

Person类

#import <Cocoa/Cocoa.h>
#import "Dog.h"

@interface Person : NSObject {
	Dog *_dog;
}
@property (retain)Dog *dog;

@end
#import "Person.h"


@implementation Person
@synthesize dog=_dog;
-(void)setDog:(Dog*)thisDog
{
	if(_dog!=thisDog)
	{
		[_dog release];
		_dog =[thisDog retain];
		[_dog setBarkCallback:^(Dog* thisDog,int count){
			NSLog(@"dog bark infom person ,id %d,count %d",[thisDog ID],count);
		}];
	}
}
-(Dog*)dog{
	return _dog;
}
-(void)dealloc{
	_dog=nil;
	[super dealloc];
}
@end

Dog类

#import <Cocoa/Cocoa.h>


@interface Dog : NSObject {
	int _ID;
	NSTimer *timer;
	int barkCount;
	//定义一个blocks变量
	void (^barkCallback) (Dog *thisDog,int count);
}
@property (assign) int ID;

-(void)setBarkCallback:(void (^)(Dog *thisDog,int count))eachbark;

@end

#import "Dog.h"


@implementation Dog
@synthesize ID=_ID;

-(void)updateTimer:(id)arg
{
	NSLog(@"dog %d bark count %d",_ID,++barkCount);
	//使用blcok来给 Person汇报一下
	if(barkCallback)
		barkCallback(self,barkCount);
}
-(void)setBarkCallback:(void (^)(Dog *thisDog,int barkcount))eachbark{
	[barkCallback release];
	barkCallback=[eachbark copy];
	
}

-(id) init
{
	if(self=[super init])
	{
		timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateTimer:) userInfo:nil  repeats:YES];
		
	}
	return self;
} 




-(void)dealloc
{
	[barkCallback release];
	[super dealloc];
}

@end

主函数

#import <Foundation/Foundation.h>
#import "Person.h"
#import "Dog.h"


int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    // insert code here...
    NSLog(@"Hello, World!");
	Person *xiaoli=[[Person alloc]init];
	Dog *dog1=[[Dog alloc]init];
	[dog1 setID:10];
	[xiaoli setDog:dog1];
	[dog1 release];
	while (1) {
		[[NSRunLoop currentRunLoop]run];
	}
    [pool drain];
    return 0;
}

运行结果如下:

初学。。多多指教。


抱歉!评论已关闭.