ObjectC基础之块(Block)学习

用Java语言来说,OC中的Block有着类的感觉。但OC的类与block又有着不同之处,OC的类有.m.h文件,即@interface@implementation。而Block却没有类,但是它有着属性。举个Block例子:

Bock基础用法:

#import <Foundation/Foundation.h>

struct Books {
	NSString *title;
	NSString *author;
	NSString *subject;
	int book_id;
}

int main(){
	struct Books Book1;

	Book1.title = @"OC编程";
	Book1.author =@"Cook";
	Book1.subject = @"OC教程";
	Book1.book_id = 88888;
	
	NSLog(@"Book1 title : %@",Book1.title);
}

结构体作为函数参数:

将结构体作为函数参数传递,与传递变量或指针的方式非常相似。

#import <Foundation/Foundation.h>

/*结构声明*/
struct Books {
	NSString *title;
	NSString *author;
	NSString *subject;
	int book_id;
}

@interface SampleClass : NSObject
/*函数声明*/
- (void) printBook:(struct Books) book;
@end

@implementation SampleClass

- (void)printBook:(struct Books) book {
	NSLog(@"Book title: %@",book.title);
}
@end

int main(){
	struct Books book1;
	
	book1.title = @"OC";
	book.author = @"Cook";
	book.subject = @"OC编程";
	book.book_id = 88888;

	SampleClass *splClass = [[SampleClass alloc] init];
	[splClass printBook: book1];
	
	return 0;
}

总结:OC的块跟对象类似。以后用到的地方还是挺多的。

更多课程请访问个人主页:

Github搭建个人博客(2019最新版,亲测

公众号:
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章