IOS 学习笔记(NSURLConnection, Singleton)PART 12
[caption id=”” align=”alignnone” width=”302”]
请大老王给我来个这个[/caption]
老婆孩子生病只能干瞪眼着急,
办公室闷热难耐盼凉风习习,
二傻子老板得空就追着你,
草包策划们见天扯闲皮,
也想过放弃或者逃离,
走在北京的春天里,
一半汗水一半泥,
大马文章为敌,
且行且珍惜,
三十二了,
想升级,
憋气,
迷。
迷?
提气!
再一级!
测试过了,
越学越牛逼,
争取天下无敌,
点点知识和才艺,
序列化装进脑袋里,
再难也应该不弃不离,
需知人靠脸面树靠活皮,
说不定哪天机会就找到你,
所以抓紧一切时间努力学习,
老婆说我和儿子支持你别着急。
NSURLConnection发送请求和加载图片
用NSData加载远程文件会占用主进程,导致整个界面卡死,这是我不能容忍的,我想Cocoa Touch一定有异步的加载办法,这样我就能在屏幕中央显示一个小菊花,让用户知道程序不是嗝屁了。这个办法就是NSURLConnection,发送一个Get http request方式如下:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]; [NSURLConnection connectionWithRequest:request delegate:self];
实现NSURLConnectionDataDelegate,并实现对应的方法:
@interface MyViewController () <NSURLConnectionDataDelegate>
@end
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
//handle error
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
//load complete do something with your receivedData
}
需要注意的是,didReceiveData收到的并非完整的Data,而是部分Data,要存储这些阶段数据,可以定义一个NSMutableData对象,并在发起请求之前重新初始化这个NSMutableData,同时在didReceiveData时,将数据附加到数据对象上。
同样的加载过程可以应用在加载图片上。由于得到的都是NSData,区别就在于结果的处理上了。
UIActivityIndicatorView
这就是那个小菊花了,用于缓解用户的焦虑(或者让用户更焦虑)。使用方式如下:
self.loadingIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; CGPoint center = CGPointMake([[UIScreen mainScreen] bounds].size.width/2,[[UIScreen mainScreen] bounds].size.height/2); [self.loadingIndicator setCenter:center]; [self.view addSubview:self.loadingIndicator];
这时它还没有被显示出来,这样显示:
[self.loadingIndicator startAnimating];
这样隐藏:
[self.loadingIndicator stopAnimating];
Singleton
OC里实现单例是这样的:
#import <Foundation/Foundation.h> @interface AppDataShare : NSObject @property(nonatomic,strong)NSString *userName; + (id)sharedData; @end
#import "AppDataShare.h"
@implementation AppDataShare
+ (id)sharedData {
static AppDataShare *shareData = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shareData = [[self alloc] init];
});
return shareData;
}
- (id)init {
if (self = [super init]) {
}
return self;
}
@end
实测自定义数据也没问题,非ARC想实现可以参考这里
字符串拆分,替换特定字符,去除空格和换行
字符串操作的方法名字都好长啊!
根据特定字符拆分:
NSString *str = @“a_b_c”;
[str componentsSeparatedByString:@“_”];
替换指定字符:
[str stringByReplacingOccurrencesOfString:@“_” withString:@””];
去除空格和换行:
[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];