oc 常用類及操作

  • NSString

    //創建常量字符串
    NSString* str1 = @"第一個字符串";
    
    //創建空字符串,並賦值
    NSString* str2 = [[NSString alloc] init];
    str2 = @"第二個字符串";
    NSString* str3 = [[NSString alloc] initWithString:@"1234"];
    
    //從文件創建字符串
    //注意編碼格式,csv用別的讀亂碼了
    NSString* str4 = [[NSString alloc] initWithContentsOfFile:@"/Users/2.csv" encoding:NSUnicodeStringEncoding error:nil];
    
    //比較是否相等
    BOOL result = [str1 isEqualToString:str2];
    NSLog(@"%d",result);
    
    //int轉字符串
    int a=1223;
    NSString* str5 = [NSString stringWithFormat:@"%d",a];//其他類似
  • NSArray

    //數組初始化,,獲取元素個數
    NSArray *arr = [NSArray arrayWithObjects:@"ss",@"dd",@"aa", nil];
    NSLog(@"%@", arr);
    NSInteger con = [arr count];
    NSLog(@"%ld", con);
    
    // 根據對象獲得索引值
    NSInteger dd = [arr indexOfObject:@"dd"];
    NSLog(@"%ld", dd);
    
    //根據索引值獲得對象
    NSArray *ppp = [arr objectAtIndex:0];
    NSLog(@"%@", ppp);
  • NSMutableArray (可變數組)

    NSMutableArray *mutarr = [NSMutableArray arrayWithCapacity:5];
    NSLog(@"%@", mutarr);
    NSMutableArray *mt = [NSMutableArray arrayWithObjects:@"aaa", @"bbb", @"ccc", @"ddd", nil];
    NSMutableArray *mm = [NSMutableArray arrayWithObjects:@"ee", @"qq", nil];
    NSLog(@"%@", mt);
    //添加元素
    [mt addObject:@"fff"];
    NSLog(@"%@", mt);
    //插入元素
    [mt insertObject:@"ooo" atIndex:2];
    NSLog(@"%@", mt);
    //數組連接
    [mt addObjectsFromArray:mm];
    NSLog(@"%@", mt);
     
    //刪除元素
    [mt removeObjectAtIndex:2];
    NSLog(@"%@", mt);
     
    //替換元素
    [mt replaceObjectAtIndex:0 withObject:@"ttttt"];
    NSLog(@"%@", mt);
     
    //交換兩個指定位置的元素
    [mt exchangeObjectAtIndex:0 withObjectAtIndex:1];
    NSLog(@"%@", mt);
  • NSDictionary

    NSArray *value =[NSArray arrayWithObjects:@"a", @"b", @"c", nil ];//無序
    NSArray *key = [NSArray arrayWithObjects:@"1", @"2", @"3",nil ];
    NSDictionary *dic2 = [NSDictionary dictionaryWithObjects:value forKeys:key];
    NSLog(@"%@", dic2);
    
    NSLog(@"%@",[dic2 objectForKey:@"1"]);//輸出key爲1 的value
    NSLog(@"%@", dic2);
    //字典長度
    NSLog(@"%lu",[dic2 count]);
    //調出所有的key值
    NSArray *allkey = [dic2 allKeys];
    NSLog(@"%@", allkey);
    
    NSDictionary *dic3 = [NSDictionary dictionaryWithObjectsAndKeys:@"aa", @11, @"bb", @22, @"cc", @"33", nil];//value-key
    NSLog(@"%@", dic3);
  • NSMutableDictionary

    //插入一個鍵值 key:1 value:a
    NSMutableDictionary *dic1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"a", @"1", nil];
    NSLog(@"%@", dic1);
    //插入兩個鍵值
    [dic1 setObject:@"c" forKey:@"3"];
    [dic1 setObject:@"d" forKey:@"4"];
    NSLog(@"%@", dic1);
    //插入一個鍵值
    [dic1 setValue:@"b" forKeyPath:@"2"];
    NSLog(@"%@",dic1);
    //對key爲5的value進行修改
    [dic1 setObject:@"bb" forKeyedSubscript:@"2"];
    NSLog(@"%@",dic1);
    //遍歷字典所有的key
    for (NSString* key in dic1) {
        NSLog(@"%@",[dic1 objectForKey:key]);
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章