swift object-c 使用

邵文乐
2023-12-01
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

 类似资料: