Wednesday, November 9, 2016

How to use barrier

Example:
https://github.com/lingzt/BarrierPra
By using the barrier, I can make sure every time getter starting after the previous setter finished.


#import "ViewController.h"

NSString *_name;
@interface ViewController ()
@property (nonatomic, strong, readwrite) NSString *name;@property (nonnull, strong, nonatomic) dispatch_queue_t syncQueue;@end
@implementation ViewController- (void)viewDidLoad {

    [super viewDidLoad];    //并行队列   set up on global queue    _syncQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);    for(int i=0; i<1000; i++){
        NSString *tempName = [NSString stringWithFormat:@"%d",i];        [self name];        [self setName:tempName];
    }

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}




//用同步  sync with global queue- (NSString *)name{
    __block NSString *localName;    dispatch_sync(_syncQueue, ^{
        localName =_name;        NSLog(@"getter");        NSLog(localName);    });    return localName;}
//利用异步栅栏块  async with global que, with barrier- (void)setName:(NSString *)name{
    dispatch_barrier_async(_syncQueue, ^{
        _name = name;        NSLog(@"settter");        NSLog(_name);    });}


@end

Monday, November 7, 2016

Effective Objective-C 2.0 study notes

in Chinese, great stuff!
http://www.cnblogs.com/purple-sweet-pottoes/p/4742552.html

http://blog.csdn.net/sanjunsheng/article/details/44371341

difference bw category & extension

Category:
1. The category .h file is optional. When it is deleted the .m file have to import the main .h file
2.  To expose the method, it has to be declared in the .h file.
3. Can't declare any new property in the category.

Extension:
1. Kinda like category,  but anonymous, what is even better,  it can declare the new property!
2. Can be used to expose read-only properties.
for example:

in main .m file, declare the internal method

@interface Account ()

@property (nonatomic, readonly) NSString* randomStuff;
+ (void)setCurrentAccount:(Account*)account;

then implement the method
+ (void)setCurrentAccount:(Account*)account
{
    currentAccount = account;}


in other class's .m file, set extension interface to expose the method to the current class.


@interface Account ()
+ (void)setCurrentAccount:(Account*)account;@end

later in this class, we will be able to call the private method.

- (void)cleanCurrentUser{
    [Account setCurrentAccount:nil];
}

Sunday, November 6, 2016

ReactiveCocoa

I have found some senior people heavily using ReactiveCocoa in the project I am currently working on. So, knowing ReactiveCocoa https://github.com/ReactiveCocoa/ReactiveCocoa is my homework of this Sunday.

Following are some material I am following today:







Study note:
It is 1:30am and I really got to go to bed. That way I will have enough energy for pairing with others tomorrow.

It was not as productive as I expected, so so far I found RAC has something to do with MVVM, which is super cool.
More reading to come: https://www.objc.io/issues/13-architecture/mvvm/

Wednesday, September 14, 2016

closure in swift

Closure is nuts!

Try run this code, and you will know what I am talking about


typealias IntegerFunction = Int -> ()

func  gamCounterSample() -> Int -> Void {
    func increment(i: Int){
        print("Integer passed in: \(i)")
    }
    return increment
}


func  gameCounter() -> IntegerFunction {
    var counter = 0
    
    func increment(i : Int){
        counter += i
        print("Counter value \(counter)")
    }
    
    return increment
}

let aCounter = gameCounter()
aCounter
aCounter(1)
aCounter(1)

Friday, September 9, 2016

tap and move collectionView

I was super pumped when found out about "installsStandardGestureForInteractiveMovement"

CollectionView is alway my go to when it comes to UI designs. Coz it makes everything more visualized, and easy to build the connection between the content and the users. 

To practice "installsStandardGestureForInteractiveMovement"
First, set up a basic collection.



import UIKit

private let reuseIdentifier = "Cell"

class PhotoCC: UICollectionViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }


    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }


    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 20
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)
        cell.backgroundColor = UIColor.grayColor()
        return cell
    }
}



Then set self.installsStandardGestureForInteractiveMovement = true
and 
    override func collectionView(collectionView: UICollectionView, moveItemAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
//code here

    }

The CollectionView will be ready to go.


The whole project is available at https://github.com/lingzt/CollectionViewTapMovePra

Thursday, September 8, 2016

partially reload tableview

Practice
1. reload section
2. reload row


I can totally see myself using these functions in the future.  Sometimes we just do not need to reload the whole tableview.

https://github.com/lingzt/TVRefreshSectionPra

Wednesday, September 7, 2016

copy and strong + swap function

basically

Copy: pass by value
Strong: pass by reference
more details: https://github.com/lingzt/CopyAndStrong



Swap function:

is to  swap values of two. 

The <T> in swap function means two value has to be of the same type. <T> does not mean any type specifically but only mean certain type in general. 





Thursday, September 1, 2016

AFNETWORKING CALL

Made a successful AFNETWORKING CALL today.
Pull a whole google task list to local via OBJC. Good progress!

https://github.com/lingzt/ToDoListPraOBJC

Sunday, August 28, 2016

Network calls





Build a basic NSURLSessionTask and pushed it to Github. 

https://github.com/lingzt/NetWorkCallPra 

Tuesday, August 23, 2016

study note: IOS之同步请求、异步请求、GET请求、POST请求


Apple is not longer supported " NSURLConnection sendSynchronousRequest "  

1、同步请求可以从因特网请求数据,一旦发送同步请求,程序将停止用户交互,直至服务器返回数据完成,才可以进行下一步操作,
2、异步请求不会阻塞主线程,而会建立一个新的线程来操作,用户发出异步请求后,依然可以对UI进行操作,程序可以继续运行
3、GET请求,将参数直接写在访问路径上。操作简单,不过容易被外界看到,安全性不高,地址最多255字节;
4、POST请求,将参数放到body里面。POST请求操作相对复杂,需要将参数和地址分开,不过安全性高,参数放在body里面,不易被捕获。

1、 同步GET请求
    //第一步,创建URL
    NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do?type=focus-c"];
     
    //第二步,通过URL创建网络请求
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    //NSURLRequest初始化方法第一个参数:请求访问路径,第二个参数:缓存协议,第三个参数:网络请求超时时间(秒)
      其中缓存协议是个枚举类型包含:
      NSURLRequestUseProtocolCachePolicy(基础策略)
      NSURLRequestReloadIgnoringLocalCacheData(忽略本地缓存)
      NSURLRequestReturnCacheDataElseLoad(首先使用缓存,如果没有本地缓存,才从原地址下载)
      NSURLRequestReturnCacheDataDontLoad(使用本地缓存,从不下载,如果本地没有缓存,则请求失败,此策略多用于离线操作)
      NSURLRequestReloadIgnoringLocalAndRemoteCacheData(无视任何缓存策略,无论是本地的还是远程的,总是从原地址重新下载)
      NSURLRequestReloadRevalidatingCacheData(如果本地缓存是有效的则不下载,其他任何情况都从原地址重新下载)
    //第三步,连接服务器
    NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
     
    NSString *str = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
     
    NSLog(@"%@",str);
//该代码片段来自于: http://www.sharejs.com/codes/objectc/5873
2、同步POST请求
    //第一步,创建URL
    NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do"];
    //第二步,创建请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    [request setHTTPMethod:@"POST"];//设置请求方式为POST,默认为GET
    NSString *str = @"type=focus-c";//设置参数
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    //第三步,连接服务器
     
    NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
     
    NSString *str1 = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
     
    NSLog(@"%@",str1);
//该代码片段来自于: http://www.sharejs.com/codes/objectc/5873
3、异步GET请求
    //第一步,创建url
    NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do?type=focus-c"];
    //第二步,创建请求
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    //第三步,连接服务器
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
//该代码片段来自于: http://www.sharejs.com/codes/objectc/5873
4、异步POST请求
    //第一步,创建url
    NSURL *url = [NSURL URLWithString:@"http://api.hudong.com/iphonexml.do"];
    //第二步,创建请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    [request setHTTPMethod:@"POST"];
    NSString *str = @"type=focus-c";
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    //第三步,连接服务器
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
//该代码片段来自于: http://www.sharejs.com/codes/objectc/5873
5、异步请求的代理方法
//接收到服务器回应的时候调用此方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
    NSLog(@"%@",[res allHeaderFields]);
    self.receiveData = [NSMutableData data];
                             
}
//接收到服务器传输数据的时候调用,此方法根据数据大小执行若干次
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.receiveData appendData:data];
}
//数据传完之后调用此方法
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *receiveStr = [[NSString alloc]initWithData:self.receiveData encoding:NSUTF8StringEncoding];
    NSLog(@"%@",receiveStr);
}
//网络请求过程中,出现任何错误(断网,连接超时等)会进入此方法
-(void)connection:(NSURLConnection *)connection
 didFailWithError:(NSError *)error
{
    NSLog(@"%@",[error localizedDescription]);
}
//该代码片段来自于: http://www.sharejs.com/codes/objectc/5873