加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift和Objective-C的不同

发布时间:2020-12-14 07:00:33 所属栏目:百科 来源:网络整理
导读:声明类 Objective-C [#Content# class] ------------------------------------------------------------------------ Swift #content#.self 打印一个对象所属类型 Objective-C // 打印一个对象所属类型 NSLog(@"%@",[object class]); Swift // 打印一个对象

声明类

Objective-C
    
    [<#Content#> class]
    
    ------------------------------------------------------------------------
    
    Swift
    
    <#content#>.self

打印一个对象所属类型

Objective-C
    
    // 打印一个对象所属类型
    NSLog(@"%@",[object class]);
Swift
    
    // 打印一个对象所属类型
    print("返回的类型是:--->(<#object#>.dynamicType )");

拿到AppDelegate

Objective-C
    
    // 拿到 AppDelegate
    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    -----------------------------------------------------------
    
    Swift
    
    // 拿到 AppDelegate
    let tempAppDelegate = UIApplication .sharedApplication().delegate as! AppDelegate;

反序列化

Objective-C
    
    // 苹果自带反序列化 返回类型id
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
    
    -------------------------------------------------
    
    Swift
    
    do {
        
        // 苹果自带反序列化
        let dict = try NSJSONSerialization.JSONObjectWithData(jsonData!,options: .AllowFragments)
        
        // 继续下一步操作
        
    } catch {
        
        print(error);
    }

类型转换和判断

Objective-C
    
    // 类型判断
    if ([<#object#> isKindOfClass:[<#Class#> class]]) {
        
        // 类型转换
        <#Class#> *<#Name#> = (<#Class#> *)<#object#>;
        
    }
    
    -------------------------------------------------
    
    Swift

    // 判断 类型
    if <#object#>.isKindOfClass(<#Class#>) == false {
        
        return;
        
    }
    
    // 类型转换
    let <#Name#> = <#object#> as! <#Class#>;

dealloc/控制器被释放

Objective-C
    // 控制器被释放时 调用此方法
    - (void)dealloc {
        printf("控制器释放");
    }
    -------------------------------------------------
    Swift
    // 析构器方法 类似于Object-C的 dealloc
    deinit {
         print("控制器释放");
    }

获取字符串长度

Objective-C

    // 获取字符串长度
    string.length
    -------------------------------------------------
    Swift
    
    // 获取字符串长度
    string.characters.count

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读