swift object-c 使用

swift and oc

  1. swift通过括号初始化属性,oc通过alloc init方式初始化.
    SWIFT
    let myTableView: UITableView = UITableView(frame: CGRectZero, style: .Grouped)

    OBJECTIVE-C
    UITableView *myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];

  2.  swift通过"点"访问或者设置属性
  SWIFT
  myTextField.textColor = UIColor.darkGrayColor()
  myTextField.text = "Hello world"
  if myTextField.editing {
      myTextField.editing = false
  }

  OBJECTIVE-C
  [myTextField text] = "Hello world";

  3. swift通过"点"访问方法
  SWIFT
  myTableView.insertSubview(mySubview, atIndex: 2)

  OBJECTIVE-C
  [myTableView insertSubview:mySubview atIndex:2];

  4. swift通过AnyObject定义protocol变量,而oc使用id
  SWIFT
  var myObject: AnyObject = UITableViewCell()

  OBJECTIVE-C
  id myObject = [[UITableViewCell alloc] init];

  5. swift不能直接使用c++代码,必须通过oc或者c

  6. 类型转换,swift变量如果有optional属性,那么转换失败对象赋为nil,而oc出现runtime error

  7. swift可以兼容oc,而swift有些属性无法转换为oc

  8. swift对象除非有optional属性,否则不能为nil。oc和swift交互得时候需要注意

  9. swift extension既可以扩展系统framework也可以扩展自定义对象,如果时基本类型那么必须是computed type,类似于oc得catagory.
   而oc里面extension无法重载已存在得属性和方法.
   SWIFT
   extension UIBezierPath {
   convenience init(triangleSideLength: Float, origin: CGPoint) {
         self.init()
         let squareRoot = Float(sqrt(3))
         let altitude = (squareRoot * triangleSideLength) / 2
         moveToPoint(origin)
         addLineToPoint(CGPoint(triangleSideLength, origin.x))
         addLineToPoint(CGPoint(triangleSideLength / 2, altitude))
         closePath()
      }
  }

  extension CGRect {
       var area: CGFloat {
       return width * height
       }
  }
  let rect = CGRect(x: 0.0, y: 0.0, width: 10.0, height: 50.0)
  let area = rect.area
  / / area: CGFloat = 500.0

  10. swift closure和oc block兼容。oc block里面使用外部变量是只读的,而swift closure里面是可修改的
  SWIFT
  let completionBlock: (NSData, NSError) -> Void = {data, error in /* ... */}

  OBJECTIVE-C
  void (^completionBlock)(NSData *, NSError *) = ^(NSData *data, NSError *error) {/* ... */}

  11. 对象比较,swift即支持对象内容(==)对比,也支持对象实例引用(===)对比,而oc只支持对象实例(==)对比。
      当swift对象转化为oc对象时,如果需要内容比较可以通过自定义isequal方法来实现。

  12. 如果swift对象不是继承于oc类,如果想在oc里面使用,那么需要设置@objc属性
  SWIFT  
  @objc(Squirrel)
  class Белка {
       @objc(initWithName:)
       init (имя: String) { /*...*/ }
       @objc(hideNuts:inTree:)
      func прячьОрехи(Int, вДереве: Дерево) { /*...*/ }
  }

  13. construct a selector with a string literal, such aslet mySelector: Selector = "tappedButton:". Because string literals can be automatically converted to selectors, you can   pass a string literal to any method that accepts a selector
  SWIFT
  import UIKit
  class MyViewController: UIViewController {
       let myButton = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
    
       init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
          super.init(nibName: nibName, bundle: nibBundle)
          myButton.targetForAction("tappedButton:", withSender: self)
      }
    
       func tappedButton(sender: UIButton!) {
          println("tapped button")
      }
  }

  14. swift类从oc类继承
  SWIFT
  import UIKit
 
  class MySwiftViewController: UIViewController {
      // define the class
  }
  
  类protocol
  SWIFT
  class MySwiftViewController: UIViewController, UITableViewDelegate {
      // define the class
  }

  OBJECTIVE-C
  @interface MySwiftViewController: UIViewController id<UITableViewDelegate>{

  }

  15. swift重载方法需要在方法前面设置override属性,oc不需要且不含有此属性

  16. swift类继承于oc类,那么swift对象释放时会调用oc类的dealloc方法,如果继承于swift类,那么会调用swift类的deinit方法

  17. swift类属性需要连接interface builder,需要设置@IBOutlet或@IBInspectable等属性
  SWIFT
  class MyViewController: UIViewController {
      @IBOutlet var button: UIButton
      @IBOutlet var textFields: UITextField[]
      @IBAction func buttonTapped(AnyObject) {
          println("button tapped!")
      }
  }

  18. swift不含有readwrite readonly属性,stored type通过var let替换,computed type通过(set get) get替换

  19. swift copy属性对应oc里面的NSCopying

  20. Core Data,swift @NSManaged对应oc里面的@dynamic,不过@NSManaged在swift里面仅用于code data,而@dynamic在oc里面不仅用于code data

  21. swift String对应oc NSString
  String -> NSString : NSString = String..capitalizedString
  NSString -> String : String NSString as String

  SWIFT
  import Foundation
  let greeting = "hello, world!"
  let capitalizedGreeting = greeting.capitalizedString
  //   capitalizedGreeting: String = Hello, World!

  SWIFT
  import Foundation
  let myString: NSString = "123"
  if let integerValue = (myString as String).toInt() {
      println("\(myString) is the integer \(integerValue)")
  }

  22. swift Array对应oc NSArray
    swift Dictionary对应oc NSDictionary
    swift 新特性Array Dictionary可以使用一些算法或者分析
    swift Array转化为oc NSArray里面的元素必须是AnyObject

  23. swift assert对应oc NSAssert,swift里面不含有NSAssert

  24. swift即可以用NSLog也可以println

  25. swift自动管理Core Foundation对象内存,不需要手动调用CFRetain, CFRelease, or CFAutorelease等.
  swift里面未自动管理的对象会显式使用关键字Unmanaged<T>,可以用过takeUnretainedValue; takeretainedValue等方法放入到arc机制里面交给系统自动管理。
  SWIFT
  func StringByAddingTwoStrings(CFString!, CFString!) -> Unmanaged<CFString>!
  let memoryManagedResult = StringByAddingTwoStrings(str1, str2).takeUnretainedValue()

  OBJECTIVE-C
  CFStringRef StringByAddingTwoStrings(CFStringRef string1, CFStringRef string2)

  26. swift is as?对应oc isKindOfClass conformsToProtocol
  SWIFT
  if object is UIButton {
      // object is of type UIButton
  } else {
      // object is not of type UIButton
  }

  SWIFT
  if let button = object as? UIButton {
       // object is successfully cast to type UIButton and bound to button
  } else {
      // object could not be cast to type UIButton
  }

  27. swift let 对应 oc #define.
  SWIFT
  let FADE_ANIMATION_DURATION = 0.35

   swift不支持complex macro

  28. 系统framework即可以用于oc,也可以用于swift

oc swift交互使用
  1. oc文件使用swift,在头文件里面包含projectname-Swift.h
  2. swift使用oc, 在projectname-Bridging-Header.h里面#import需要包含的头文件

第三方库
  1. AFNetworking SVProgressHUD CocoaHttpServer WebViewJavascriptBridge等可以按照"oc swift交互使用"里面的使用原则来使用
  2. 如果使用在oc和swift特性上面有冲突,可以通过使用新的oc类来适配
  3. swift使用c++库,需要通过oc来适配

swift运行环境

  OS: ios OS X

IOS

  开发环境:
  OS X Mavericks 10.9.3 or later
  软件环境:
  ios6.0 or later
  硬件设备: 
  iPad:
  iPad Air (Model A1474)
  iPad Air (Model A1475)
  iPad Air (Model A1476)
  iPad mini (Model A1489)
  iPad mini (Model A1490)
  iPad mini (Model A1491)
  iPad (4th generation Model A1458)
  iPad (4th generation Model A1459)
  iPad (4th generation Model A1460)
  iPad mini (Model A1432)
  iPad mini (Model A1454)
  iPad mini (Model A1455)
  iPad Wi-Fi (3rd generation)
  iPad Wi-Fi + Cellular (model for ATT)
  iPad Wi-Fi + Cellular (model for Verizon)
  iPad 2 Wi-Fi (Rev A)
  iPad 2 Wi-Fi
  iPad 2 Wi-Fi + 3G (GSM)
  iPad 2 Wi-Fi + 3G (CDMA)

  iPhone:
  iPhone 5s (Model A1453, A1533)
  iPhone 5s (Model A1457, A1518, A1528, A1530)
  iPhone 5c (Model A1456, A1532)
  iPhone 5c (Model A1507, A1516, A1526, A1529)
  iPhone 5 (Model A1428)
  iPhone 5 (Model A1429)
  iPhone 4s
  iPhone 4

  iPod touch:
  iPod touch (5th generation)

  or later

OS X:
  开发环境:
  OS X Mavericks 10.9.3 or later
  软件环境:
  OS X 10.4 or later
  硬件环境:
  可以运行OS X 10.4 or later

SwiftUI is a new framework introduced by Apple in 2019 for building user interfaces on all Apple platforms (iOS, iPadOS, macOS, watchOS, and tvOS). It provides a new way of declaratively building user interfaces using Swift code. Objective-C, on the other hand, is an object-oriented programming language that has been widely used for building Mac and iOS applications. It has been around for much longer than SwiftUI, and has a large and established developer community. Here are some key differences between the two: 1. Syntax: SwiftUI has a simpler and more intuitive syntax compared to Objective-C, which can be more verbose and difficult to read. 2. Declarative vs Imperative: SwiftUI is a declarative framework, which means you describe what your user interface should look like, and the framework takes care of rendering it on the screen. Objective-C, on the other hand, is an imperative language, which requires you to write code to manipulate the user interface elements directly. 3. Interoperability: SwiftUI and Objective-C can coexist in the same project, and it is possible to use SwiftUI components in Objective-C code. However, the reverse is not true, as Objective-C code cannot be used in SwiftUI. 4. Learning Curve: SwiftUI is generally considered easier to learn for new developers, whereas Objective-C has a steeper learning curve. Ultimately, the choice between SwiftUI and Objective-C depends on the specific needs and preferences of each developer and the project they are working on. Both frameworks have their strengths and weaknesses, and both can be used to build high-quality and performant applications.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值