IOS_OC_基礎語法 – iPhone手機開發技術文章 iPhone軟體開發教學課程

1.YES與NO

Object-c 提供瞭 BOOL 類型, 但這個BOOL 類型和 C++裡的並不一樣: 在C++裡一切非 0 值的東西都 為 true,而為 0 值的為 false。但是 Object-c 裡 1 為 true 並被宏定義為 YES=1,0 為 false 並被宏定義為 NO=0。

+ (BOOL)isEquals:(int)x with:(int)y
{
    return x - y;
}
if ([Provider isEquals:10 with:1021]) {// == YES //error
        NSLog(@" !!!!!!");
 } else {
        NSLog(@" ===== ");
 }

2.類CLass

在OC的一個類中,不允許重復定義一個函數,區分函數是否重復根據方法名,與接收參數無關。與java不同

pubic void getInfo(Animal a);
public void getInfo(Person p);

//同一個方法getInfo:
- (void)getInfo:(Animal)a;
- (void)getInfo:(Person)p;

3.常見的集合

void arrayTest()
{
    NSArray *array = [NSArray arrayWithObjects:@"one", @"two", @"three", nil];
    NSLog(@"len = %lu", [array count]);
    for (NSObject *obj in array) {
        NSLog(@"== %@", obj);
    }
    for (int i=0; i<[array count]; i++) {
        NSLog(@"%@", [array objectAtIndex:i]);
    }
    //寫進文件,atomically是否先將文件保存至臨時文件中,待保存成功之後,再與原始文件替換,是一種安全機制。
    [array writeToFile:@"/Users/zf/Desktop/1.txt" atomically:YES];
    //讀取文件
    NSArray *arr = [NSArray arrayWithContentsOfFile:@"/Users/zf/Desktop/1.txt"];
    NSLog(@"len3 = %lu", [arr count]);
    
}
void mutableArrayTest()
{
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:3];
    [array addObject:@"one"];
    [array addObject:@"two"];
    [array addObject:@"three"];
    [array addObject:@"two1"];
    
    NSLog(@"len = %lu", [array count]);
    [array removeObjectAtIndex:3];
    NSLog(@"len = %lu", [array count]);
    
    NSEnumerator *e = [array objectEnumerator];
    NSString *x;
    while (x = [e nextObject]) {
        NSLog(@"x == %@", x);
    }
    NSEnumerator *e1 = [array reverseObjectEnumerator];
}
void dictTest()
{
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"value1", @"key1", @"value2", @"key2", nil];
    NSLog(@"%@", [dict objectForKey:@"key2"]);
    
    NSMutableDictionary *d = [NSMutableDictionary dictionaryWithCapacity:3];
    
    [d setObject:@"wwwwww" forKey:@"key1"];
    [d removeObjectForKey:@"key1"];
    NSLog(@"%lu, key1=%@", [d count], [d objectForKey:@"key1"]);
}

NSArray:有序集合,元素在一個整塊的內存中並按序排列;

NSSet:無序集合,散列存儲。
讀developer.apple關於NSSet的解釋:You can use sets as an alternative to arrays when the order of elements isn’t important and performance in testing whether an object is contained in the set is a consideration—while arrays are ordered, testing for membership is slower
than with sets.
搜索一個元素,NSSet的效率會比NSArray高。為什麼呢?原理比較簡單:NSSet中元素的存儲和訪問都是一個hash的過程。比如你要存儲元素A,一個hash算法直接就能直接找到A應該存儲的位置;同樣,當你要訪問A時,一個hash過程就能找到A存儲的位置。而對於NSArray,若想知道A到底在不在數組中,則需要一個一個元素比較,顯然效率不高。

4.NSString

void stringTest()
{
    NSString *str = [NSString stringWithFormat:@"aa,bb,cc,"];
    NSArray *array = [str componentsSeparatedByString:@","];
    NSLog(@"len = %lu", [array count]);
    
    NSLog(@"%@", [array componentsJoinedByString:@"-"]);
}

You May Also Like