惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
SegmentFault 最新的问题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
B
Blog RSS Feed
Y
Y Combinator Blog
T
Tailwind CSS Blog
博客园 - 三生石上(FineUI控件)
J
Java Code Geeks
Stack Overflow Blog
Stack Overflow Blog
aimingoo的专栏
aimingoo的专栏
Jina AI
Jina AI
The GitHub Blog
The GitHub Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
A
About on SuperTechFans
H
Hackread – Cybersecurity News, Data Breaches, AI and More
D
Docker
酷 壳 – CoolShell
酷 壳 – CoolShell
C
Check Point Blog
M
MIT News - Artificial intelligence
Last Week in AI
Last Week in AI
V
V2EX
腾讯CDC
F
Fortinet All Blogs
博客园 - 叶小钗
T
The Blog of Author Tim Ferriss

博客园 - 观海云不远

ChatView:把 ChatGPT / Claude 对话保存、分享和发布成独立网页 AI对普通人到底有什么用?这8个场景告诉你答案 用 AI 做点不一样的事:你出想法,我来实现 Python 调试工具PDB的基本使用 帮园子算账省钱 linux I/O性能优化 Linux内存问题排查工具 CPU优化方案 系统中出现大量不可中断进程和僵尸进程怎么办? CPU 使用率过高怎么办 CPU上下文切换 到底应该怎么理解“平均负载”? iOS开发学习笔记(OC语言)——调起APP(URL Scheme) iOS开发学习笔记(OC语言)——文件基本操作 iOS开发学习笔记(OC语言)——网络请求 iOS开发学习笔记(OC语言)——底部tab栏 iOS开发学习笔记(OC语言)——线程安全的单例 iOS开发学习笔记(OC语言)——UIView和UIViewController生命周期 Jenkins安装配置回滚 Mac 下反编译Android APK
iOS开发学习笔记(OC语言)——block使用示例
观海云不远 · 2022-03-15 · via 博客园 - 观海云不远
//
//  ViewController.m
//  ladder
//
//  Created by xxx on 2022/3/9.
//

#import "ViewController.h"

@interface ViewController()

@property(nonatomic, strong, readwrite) NSTextField *infoLabel;
@property(nonatomic, strong, readwrite) NSButton *infoBtn;
@property(nonatomic, strong) dispatch_queue_t queue;

typedef void (^writeProgress)(int progress);

-(void)writeFile:(NSString *)fileName content:(NSString *)content progress:(writeProgress) progress;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _queue = dispatch_queue_create("rwqueue", DISPATCH_QUEUE_CONCURRENT);
    
    [self.view addSubview:({
        self.infoLabel = [[NSTextField alloc]initWithFrame:CGRectMake(10, 10, self.view.frame.size.width - 20, self.view.frame.size.height - 80)];
        self.infoLabel;
    })];
    
    [self.view addSubview:({
        self.infoBtn = [[NSButton alloc]initWithFrame:CGRectMake(10,self.infoLabel.frame.size.height + 20, self.view.frame.size.width - 20, 50)];
        self.infoBtn.bordered = NO;
        self.infoBtn.wantsLayer = YES;
        self.infoBtn.layer.backgroundColor = [NSColor blueColor].CGColor;
        self.infoBtn.layer.cornerRadius = 5;
        [self setButtonTitleFor:self.infoBtn toString:@"Click Me" withColor:[NSColor whiteColor]];
        [self.infoBtn setTarget:self];
        [self.infoBtn setAction:@selector(_btnClick)];
        self.infoBtn;
    })];
    
}

- (void)setButtonTitleFor:(NSButton*)button toString:(NSString*)title withColor:(NSColor*)color{
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setAlignment:NSTextAlignmentCenter];
    NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:color, NSForegroundColorAttributeName, style, NSParagraphStyleAttributeName, nil];
    NSAttributedString *attrString = [[NSAttributedString alloc]initWithString:title attributes:attrsDictionary];
    [button setAttributedTitle:attrString];
}

-(void)_btnClick{
    __weak __typeof(&*self)weakSelf = self;
    dispatch_async(_queue, ^{
        [self writeFile:@"test.txt" content:@"Hello IOS!" progress:^(int progress) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"block current threadid: %@", [NSThread currentThread]);
                weakSelf.infoLabel.stringValue = [NSString stringWithFormat:@"progress: %d%%", progress];
            });
        }];
    });
    
}

-(void)writeFile:(NSString *)fileName content:(NSString *)content progress:(writeProgress) progress{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [paths firstObject];

    NSFileManager *fileManager = [NSFileManager defaultManager];

    //创建文件
    NSString *listDataPath = [cachePath stringByAppendingPathComponent:fileName];
    [fileManager createFileAtPath:listDataPath contents:nil attributes:nil];

    //查询文件
    BOOL fileExist = [fileManager fileExistsAtPath:listDataPath];

    if (fileExist) {
        //文件追加内容
        NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:listDataPath];
        [fileHandle seekToEndOfFile];
        
        NSMutableArray *listItems = [NSMutableArray array];
        for (int i = 0; i < [content length]; i++) {
            NSString *ch = [content substringWithRange:NSMakeRange(i, 1)];
            [listItems addObject:ch];
            [listItems addObject:@"\n"];
        }
        
        for (int i = 0; i < listItems.count; i++) {
            [fileHandle writeData:[listItems[i] dataUsingEncoding:NSUTF8StringEncoding]];
            sleep(2);
            if (progress) {
                NSLog(@"current threadid: %@", [NSThread currentThread]);
                progress((int)((i+1)*1.0/listItems.count * 100));
            }
        }
        
        [fileHandle synchronizeFile];
        [fileHandle closeFile];
    }
}

@end