韌館-LearnHouse

[iOS]Objective-C常用的Cocoa Touch API

dispatch_async

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // 耗时的操作
    dispatch_async(dispatch_get_main_queue(), ^{
        // 更新界面
    });
}); 

example:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSURL * url = [NSURL URLWithString:@"http://learn-house.idv.tw/xxx.jpg"];
    NSData * data = [[NSData alloc]initWithContentsOfURL:url];
    UIImage *image = [[UIImage alloc]initWithData:data];
    if (data != nil) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.imageView.image = image;
         });
    }
});
serial 的 queue
dispatch_async(dispatch_queue_create("com.learnhouse.queue", DISPATCH_QUEUE_SERIAL), ^{
 //your code
});

NSDictionary

//一個key - value
NSDictionary *dic1 = [NSDictionary dictionaryWithObject:@"@123" forKey:@"key1"];
//兩個以上 key - value
NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1",@"value2",@"key2" ,nil];
//用字典為另一個子字典初始化
NSDictionary *dic3 = [NSDictionary dictionaryWithDictionary:dic1]
//新方法賦值
NSDictionary *dic4 = @{@"key1": @"value1",@"key2": @"value2"};
//以為件內容初始化一個字典
NSDictionary *dic5 = [NSDictionary dictionaryWithContentsOfFile:path];
//將字典的key轉成一個枚舉對象,用於遍歷
NSEnumerator *enumerator = [dic4 keyEnumerator];
//將字典的value轉成一個枚舉對象,用於遍歷
NSEnumerator *enumerator = [dic6 objectEnumerator];

字典的常用方法

//返回字典鍵值對的個數
NSInteger count = [dic4 count];
//通過key獲取對應的value對象
NSObject *object = [dic2 objectForKey:@"key1"];
//獲取所有鍵的集合
NSArray *keys = [dic3 allKeys];
//獲取所有值的集合
NSArray *values = [dic3 allValues];

NSMutableDictionary

可變字典與不可變字典的初始化方法相同,但不能用新方法。下面只介紹常用方法

常用方法

NSMutableDictionary *dic6 = [NSMutableDictionary dictionary];
//像字典中追加一個新的 key5 和 value5
[dic6 setObject:@"value5" forKey:@"key5"];
//像字典中添加整個字典對象
[dic6 addEntriesFromDictionary:dic1];
//將字典6的對象內容設置與字典1的對象內容相同
[dic6 setDictionary:dic1];
//刪除鍵所對應的鍵值對
[dic6 removeObjectForKey:@"key1"];
//刪除數組中的所有key 對應的鍵值對
NSArray *array = @[@"key1",@"key2",@"key3"];
[dic6 removeObjectsForKeys:array];
//移除字典中的所有對象
[dic6 removeAllObjects];

一般遍歷

for (int i = 0; i < [dic3 count]; i++) {
    id key = [keys objectAtIndex:i];
    id obj = [dic3 objectForKey:key];
    NSLog(@"%@",obj);
}

快速遍歷

for (id key in dic3) {
    id obj = [dic3 objectForKey:key];
    NSLog(@"%@",obj);
}

枚舉的辦法遍歷

NSEnumerator *enumerator = [dic4 keyEnumerator];
id key = [enumerator nextObject];
while (key) {
    id obj = [dic4 objectForKey:key];
    NSLog(@"%@",obj);
    key = [enumerator nextObject];
}

寫入BOOL值

[dicTemp setObject:[NSNumber numberWithBool:YES] forKey:@"is_default"];
//or
dicTemp[@"is_default"] = @YES;

NSString

切字串的方法
(NSString *)substringFromIndex:(NSUInteger)anIndex
(NSString *)substringToIndex:(NSUInteger)anIndex
(NSString *)substringWithRange:(NSRange)aRange

example:

NSString *str = @"1234567890";
NSLog(@"Original String: %@", str);
NSLog(@"substringFromIndex: 5 ==> %@", [str substringFromIndex:5]);
NSLog(@"substringToIndex: 5 ==> %@", [str substringToIndex:5]);
NSLog(@"substringWithRange: from 7, length 3 ==> %@", [str substringWithRange:NSMakeRange(7, 3)]);

result:

Original String: 1234567890
substringFromIndex: 5 ==> 67890
substringToIndex: 5 ==> 12345
substringWithRange: from 7, length 3 ==> 890

字串取代
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target
withString:(NSString *)replacement

example:

NSString *str = @"This is a string";
str = [str stringByReplacingOccurrencesOfString:@"string"
                                     withString:@"duck"];
//This is a duck

前戳字串比對

if ([myString hasPrefix:@"http"]) {
}

NSString 和 NSDate 互相轉換

由 NSDate 轉換為 NSString:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@", strDate);

由 NSString 轉換為 NSDate:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString:@"2010-08-04 16:01:03"];
NSLog(@"%@", date);

char 轉換成 NSString

char myChar = 'r';
[NSString stringWithFormat:@"%c" , myChar];

NSString 轉換成 char

const char *myChar = [myString UTF8String];

数组中的最大值跟最小值

NSArray * arr = [NSArray arrayWithObjects:@"1",@"10",@"5", @"31", nil];
//得到数组中最小的值
NSInteger min = [[arr valueForKeyPath:@"@min.intValue"] integerValue];
//得到数组中最大的值
NSInteger max = [[arr valueForKeyPath:@"@max.intValue"] integerValue];
NSLog(@"min = %ld  max = %ld", (long)min, (long)max);

Split an NSString

NSArray* foo = [@"10/04/2011" componentsSeparatedByString: @"/"];
NSString* firstBit = [foo objectAtIndex: 0];

UITextField

http://learn-house.idv.tw/?p=1990

偵測view的返回back button

-(void) viewWillDisappear:(BOOL)animated {
    if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) {
        // Navigation button was pressed. Do some stuff
        [self.navigationController popViewControllerAnimated:NO];
    }
    [super viewWillDisappear:animated];
}

Operation Queues的使用

NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];  //main queue
NSOperationQueue *queue = [[NSOperationQueue alloc] init]; //other queue
queue.maxConcurrentOperationCount = 1;//1 is mean serial, others are mean concurrent
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
                //任務執行
}];
[queue addOperation:operation];

or

NSOperationQueue *oprationQueue = [[NSOperationQueue alloc] init];
[oprationQueue addOperationWithBlock:^{
    //your code
}];

NSInvocationOperation

NSOperationQueue *oprationQueue = [[NSOperationQueue alloc] init];
oprationQueue.maxConcurrentOperationCount = 2;//設置最大並發數數

//NSInvocationOperation 為NSOperation的具體子類,是一個非並發操作。
NSInvocationOperation *invation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(action:) object:@"2.1"];
[oprationQueue addOperation:invation];//將任務添加到列隊中

//第二個任務
NSInvocationOperation *invation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(action:) object:@"2.2"];
invation2.queuePriority = NSOperationQueuePriorityVeryHigh;//設置invation2線程優先級
[oprationQueue addOperation:invation2];

NSThread & NSTimer

//NSThread
[NSThread sleepForTimeInterval:5];

//NSTimer
[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(yourmethod:) userInfo:nil repeats:NO];

//傳遞userInfo
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setObject:str1 forKey:@"KEY1"];
[dic setObject:str2 forKey:@"KEY2"];

[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(yourmethod:) userInfo:dic repeats:NO];


-(void)yourmethod:(NSTimer *)timer{
    NSMutableDictionary *dic = timer.userInfo;
    NSString *str1 = [dic objectForKey:@"KEY1"];
    NSString *str2 = [dic objectForKey:@"KEY2"];
}
2017年1 月 posted by admin in 程式&軟體 and have No Comments

Place your comment

Please fill your data and comment below.
名稱:
信箱:
網站:
您的評論: