• Objective-C基础知识


    1 self  是一个指针 表示当前调用该方法的对象本身

       super 不是指针  表示调用父类方法的关键字

    2 成员变量权限

    @public   公开的   可以不通过setter/getter访问

    @private   私有的   可以使用setter/getter访问      不能被继承

    @protected  受保护的(默认权限)可以使用setter/getter访问  可以被继承,

    @package   框架内可以访问  框架外不可以访问

    3 设计模式:解决一些特定的业务逻辑而设计的代码逻辑。

    4 static:修饰局部变量、只初始化一次、静态局部变量在函数调用结束后不会释放,且保留之前的值。

    单例模式:

    + (instancetype)sharedInstance {
        static Person *instance = nil;
        @synchronized (self) {
            if (instance == nil) {
                instance = [[self alloc] init];
            }
        }
      
    return instance; } + (instancetype)sharedInstance { static Person *instance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ instance = [[self alloc] init]; }); return instance; }

     5 多态:相同的消息,不同的响应。

       静态类型:可以在编译时进行查错而不是在运行时 Boy *tom = [Boy new];

       动态类型:可以方便扩展 id lucy = [Girl new];

    6 归档、解档

        Plist文件中只能存放NSArray NSDictionary NSString NSNumber NSData NSDate Bool

        自定义对象如果想写入Plist文件,需要进行归档处理(把它封装成NSData类型)

        使用NSKeyedArchive来归档

    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:p1]

        归档前需要对象所属的类实现NSCoding协议

    //归档的方法
    - (void)encodeWithCoder:(NSCoder *)aCoder {
         [aCoder encodeObject:self.name forKey:@"name"];
         [aCoder encodeInteger:self.age forKey:@"age"];
    }
    
    //解档的方法
    - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder {
      self = [super init];
      if (self) {
        self.name = [aDecoder decodeObjectForKey:@"name"];
         self.age = [aDecoder decodeIntegerForKey:@"age"];  
      }
    return self;
    }

        使用NSKeyedUnArchive来解档

    id obj = [NSKeyedUnArchive unarchiveObjectWithData: data]; 

    7 沙盒路径和应用程序束

    应用程序束 不支持写入操作 通过[NSBundle mainBundle]获取文件

    [[NSBundle mainBundle] pathForResource: “dataList” ofType: @“plist”]

    沙盒路径中的文件 支持读写操作

    沙盒根目录: NSHomeDirectory()

    沙盒根目录下有三个文件夹:Documents, Library, tmp

    获取Documents文件夹目录

    NSString *documentPath = [NSHomeDirectory() stringByAppendingPathComponent: @“Documents”];

    获取Documents文件夹下文件的目录

    NSString *filePath = [documentPath stringByAppendingPathComponent: @“myList.plist”] 

    Documents: 保存应用程序运行时生成的需要持久化的数据,iTunes同步数据时会备份该目录。

    tmp: 保存应用程序运行时所需的临时数据,使用完毕后再将相应的文件从目录删除。应用没有运行时,系统也可能会清楚该目录下的文件。iTunes同步设备时不会备份该目录。

    Library/Caches:保存应用运行时生成的需要持久化的数据,iTunes同步设备不会备份该目录。一般存储体积大、不需要备份的非重要数据,比如网络数据缓存到Caches中。

    Library/Prefrence:保存应用的所有偏好设置,如iOS中Settings设置会在该目录下查找应用的设置信息,iTunes同步时会被分该目录。

    8 异常处理

    id value = [[Person alloc] init];
        @try {
            // 可能会出现问题的代码
            [value length];
        } @catch (NSException *exception) {
    // 捕获异常,打印异常 NSLog(@"name: %@, reson: %@", exception.name, exception.reason); } @finally { // 不管有无异常都会执行这里的代码 NSLog(@"程序正常进行"); }

    也可以自己定义异常 需要继承NSException

    抛出异常 @throw exception

    9 NSDate

    [NSDate distantPast]     //很久很久以前 数学中的负无穷

    [NSDate distantFuture]    //很久很久以后 数学中的正无穷  

    构建时间格式对象

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
     /*
      Y y 年
      M   月
      D   日
      H   时(24小时制)
      h   时(12小时制)
      m   分
      s   秒
      */
     [formatter setDateFormat:@"HH:mm:ss"];
    NSString
    *dateString = [formatter stringFromDate:[NSDate date]]; NSLog(@"%@", dateString);

     10 文件管理类 NSFileManager

    // 创建文件管理对象---单例
            NSFileManager *fm = [NSFileManager defaultManager];
    
            // 判断文件是否存在
            if([fm fileExistsAtPath:@"/Users/zhangxiao/Desktop/myfile.c"]) {
                NSLog(@"file.c文件存在");
            } else {
                NSLog(@"file.c文件不存在");
            }
            
            NSData *strData = [NSData dataWithBytes:@"hello world" length: 15];
            
            // 创建文件
            if([fm createFileAtPath:@"/Users/zhangxiao/Desktop/myfile1.c" contents:strData attributes:nil]) {
                NSLog(@"file1.c文件创建成功");
            } else {
                NSLog(@"file1.c文件创建失败");
            }
            
            // 创建文件夹
            if([fm createDirectoryAtPath:@"/Users/zhangxiao/Desktop/myfiles" withIntermediateDirectories:YES attributes:nil error:nil]) {
                NSLog(@"文件夹创建成功");
            } else {
                NSLog(@"文件夹创建失败");
            }
            
            // 移动文件(必须是全路径)--可以给文件重新命名
            if([fm moveItemAtPath:@"/Users/zhangxiao/Desktop/myfiles/myfile1.c" toPath:@"/Users/zhangxiao/Desktop/myfiles/myfile3.c" error:nil]) {
                NSLog(@"文件移动成功");
            } else {
                NSLog(@"文件移动失败");
            }
            
            // 复制文件
            if([fm copyItemAtPath:@"/Users/zhangxiao/Desktop/myfiles/myfile3.c" toPath:@"/Users/zhangxiao/Desktop/myfiles/myfile1.c" error:nil]) {
                NSLog(@"文件copy成功");
            } else {
                NSLog(@"文件copy失败");
            }
            
            // 删除文件----不会删除到垃圾箱,杀出后就彻底找不回来了
            if([fm removeItemAtPath:@"/Users/zhangxiao/Desktop/myfiles/myfile3.c" error:nil]) {
                NSLog(@"删除成功");
            } else {
                NSLog(@"删除失败");
            }

     11 文件操作类 NSFileHandle

      // 以writing方式打开文件
            NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:@"/Users/zhangxiao/Desktop/myfile1.c"];
            
            // 将字符串转换为NSData
            NSData *data = [@"Hello world." dataUsingEncoding: NSUTF8StringEncoding];
            
            // 写入文件
            [fh writeData:data];
    
            // 强制写入磁盘
            [fh synchronizeFile];
    
            // 以writing方式打开的文件,无法读取数据
            NSData *myData = [fh readDataOfLength:10];
            
            if (myData) {
                NSString *string = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
                NSLog(@"string: %@", string);    // 读取到的数据为空
            }
            
            
            
            // 以reading的方式打开文件
            NSFileHandle *fh1 = [NSFileHandle fileHandleForReadingAtPath:@"/Users/zhangxiao/Desktop/myfile1.c"];
            // 指定字符个数读取文件
            NSData *data1 = [fh1 readDataOfLength:3];
            // 从当前fh指针的位置读取到文件末尾
            data1 = [fh1 readDataToEndOfFile];
            
            // 设置当前指针的偏移量---0表示文件中数据开始的位置
            [fh1 seekToFileOffset:0];
            
            // 设置当前指针到文件数据的末尾
            [fh1 seekToEndOfFile];
            
            if (data1) {
                NSString *string = [[NSString alloc] initWithData:data1 encoding:NSUTF8StringEncoding];
                NSLog(@"string: %@", string);
            }
            
            //以可读可写方式打开文件
            NSFileHandle *fh2 = [NSFileHandle fileHandleForUpdatingAtPath:@"/Users/zhangxiao/Desktop/myfile1.c"];
            
            // 没有文件关闭函数,不操作文件指针fh时,会自动关闭文件
            

     12 可变字符串NSMutableString

     NSMutableString *myString = [[NSMutableString alloc] initWithCapacity:1];
            
            NSLog(@"myString: %@", myString);       //myString:
            
            // 操作的是可变字符串本身的内存空间----insertString:atIndex  appendString   appendFormat
            [myString insertString:@"dancer" atIndex:0];
            
            NSLog(@"myString: %@", myString);      //myString: dancer
            
            [myString appendString:@" is a "];
            
            NSLog(@"myString: %@", myString);       //myString: dancer is a
            
            [myString appendFormat:@" %@ ", @"teacher"];
            
            NSLog(@"myString: %@", myString);       //myString: dancer is a  teacher
            
            // stringByAppendingString: 这是一个NSString的方法,该方法会生成一个新的字符串,原字符串是不会改变的
            NSString *otherString = [myString stringByAppendingString:@" good"];
            
            NSLog(@"myString: %@", myString);       //myString: dancer is a  teacher
            NSLog(@"otherString: %@", otherString); //otherString: dancer is a  teacher  good
            
            // 删除指定位置的字符
            NSMutableString *string = [NSMutableString stringWithString:@"北京欢迎你"];
            // 可以处理汉字的字符串
            [string deleteCharactersInRange:NSMakeRange(0, 2)];
            NSLog(@"string: %@", string);           //string: 欢迎你
            
            // 拼接路径
            NSString *filePath = [string stringByAppendingPathComponent:@"file.c"];
            NSLog(@"string: %@", string);           //string: 欢迎你
            NSLog(@"filePath: %@", filePath);       //filePath: 欢迎你/file.c
            
            // 字符串的切割
            NSString *path = @"/Users/zhangxiao/Desktop/file1.c";
            NSArray *arr = [path componentsSeparatedByString:@"/"];
            NSLog(@"array: %@", arr);               // array: ("", Users, zhangxiao, Desktop, "file1.c")
            
            NSString *compString = [arr componentsJoinedByString:@"-"];
            NSLog(@"compString: %@", compString);   //compString: -Users-zhangxiao-Desktop-file1.c 

     13 内存管理黄金法则

      (1)一个对象被alloc new copy mutableCopy时,引用计数置为1;

      (2)如果想持有一个对象的使用权,可以使用retain消息给对象的引用计数+1;

      (3)如果想释放一个对象的使用权,可以向对象发送release消息,使对象的引用计数-1;

      (4)当一个对象的引用计数为0时,自动调用dealloc方法释放对象。

    14 block

      block类型:

      (1)NSGlobalBlock:不访问外部变量的block

      (2)NSStackBlock:栈区的block(MRC下)  

      (3)NSMallocBlock:堆区的block 

            void(^block)() =^{
                NSLog(@"xxxx");
            };
            
            NSLog(@"%@", block);                // MRC: <__NSGlobalBlock__>   ARC: <__NSGlobalBlock__>
            
            int m = 10;
            void (^block1)(int a) = ^(int a) {
                NSLog(@"%d   %d", a, m);
            };
            
            NSLog(@"%@", block1);               // MRC: <__NSStackBlock__>    ARC: <__NSMallocBlock__>
            
            void (^block2)(int a) = [block1 copy];
            
            NSLog(@"%@", block2);               // MRC: <__NSMallocBlock__>   ARC: <__NSMallocBlock__>

       以下代码中 __block作用:把被访问的变量封装成一个结构体,被访问的变量作为这个结构体的成员,把这个结构体的指针复制到block块内访问。

            __block int m = 10;
            void (^block1)(int a) = ^(int a) {
                m = 20;
                NSLog(@"%d   %d", a, m);
            };
            
            block1(12);    
  • 相关阅读:
    Qt ------ QPainter 和控件组件的重绘
    Qt error ------ no matching function for call to QObject::connect(QSpinBox*&, <unresolved overloaded function type>, QSlider*&, void (QAbstractSlider::*)(int))
    DHCP 服务器功能
    matlab --- plot画图
    网站跨域解决方案有哪些
    分布式Session一致性解决方案有哪些?
    博客收集
    idea快捷键
    Linux打包、压缩与解压详解
    lastIndex()与IndexOf()的区别
  • 原文地址:https://www.cnblogs.com/muzijie/p/6420362.html
Copyright © 2020-2023  润新知