用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的块跟对象类似。以后用到的地方还是挺多的。
更多课程请访问个人主页:
公众号: