首页 > 趣闻 > 正文内容

从零入门:iOS函数调用的完整步骤与代码示例

趣闻2025-05-19 14:52:51

场景一:按钮点击时执行特定操作

??问题描述??
新手开发者想要实现点击按钮后弹出提示框,但不知道如何绑定事件。

??解决步骤??

  1. ??定义响应函数??

    • ??Swift版本??
      swift复制
      @IBAction func showAlertButtonClicked(_ sender: UIButton) {  
          let alert = UIAlertController(title: "提示", message: "按钮被点击", preferredStyle: .alert)  
          alert.addAction(UIAlertAction(title: "确定", style: .default))  
          self.present(alert, animated: true)  
      }  
    • ??Objective-C版本??
      objective复制
      - (IBAction)showAlertButtonClicked:(UIButton *)sender {  
          UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"  
                                                                         message:@"按钮被点击"  
                                                                  preferredStyle:UIAlertControllerStyleAlert];  
          [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];  
          [self presentViewController:alert animated:YES completion:nil];  
      }  
  2. ??关联按钮事件??

    • 在Interface Builder中按住Ctrl键拖拽按钮到代码的@IBAction方法
    • 或手动通过代码绑定:
      swift复制
      button.addTarget(self, action: #selector(showAlertButtonClicked(_:)), for: .touchUpInside)  
  3. ??常见问题排查??

    • 检查函数是否添加@IBAction/- (IBAction)
    • 确认按钮的??Touch Up Inside??事件已连接

场景二:页面跳转时传递数据

??问题描述??
需要从首页跳转到详情页,并将用户选择的商品ID传递给下一个页面。

??解决步骤??

  1. ??在目标页面定义接收函数??

    • ??Swift版本??(在详情页VC中)
      swift复制
      var productID: String?  
      
      func setupWithProductID(_ id: String) {  
          productID = id  
          print("接收到的ID:\(id)")  
      }  
    • ??Objective-C版本??
      objective复制
      @property (strong, nonatomic) NSString *productID;  
      
      - (void)setupWithProductID:(NSString *)productID {  
          _productID = productID;  
          NSLog(@"接收到的ID:%@", productID);  
      }  
  2. ??跳转时调用目标函数??

    swift复制
    // Swift跳转代码  
    let detailVC = DetailViewController()  
    detailVC.setupWithProductID("12345")  
    self.navigationController?.pushViewController(detailVC, animated: true)  
    objective复制
    // Objective-C跳转代码  
    DetailViewController *detailVC = [[DetailViewController alloc] init];  
    [detailVC setupWithProductID:@"12345"];  
    [self.navigationController pushViewController:detailVC animated:YES];  
  3. ??避免空值传递??

    • 使用可选类型(Swift)或nil检查(Objective-C)
    • 在调用前验证数据有效性:
      swift复制
      guard !productID.isEmpty else {  
          print("ID不能为空")  
          return  
      }  

场景三:网络请求完成后的数据处理

??问题描述??
需要从API获取用户列表数据,并在请求成功后刷新表格。

??解决步骤??

  1. ??定义网络请求函数??

    swift复制
    func fetchUserList(completion: @escaping ([User]) -> Void) {  
        guard let url = URL(string: "https://api.example.com/users") else { return }  
        URLSession.shared.dataTask(with: url) { data, _, _ in  
            guard let data = data,  
                  let users = try? JSONDecoder().decode([User].self, from: data)  
            else { return }  
            DispatchQueue.main.async {  
                completion(users) // 主线程回调  
            }  
        }.resume()  
    }  
  2. ??调用函数并处理结果??

    swift复制
    fetchUserList { [weak self] users in  
        self?.userList = users  
        self?.tableView.reloadData()  
    }  
  3. ??错误处理增强??

    • 添加网络状态码判断(如404/500)
    • 增加加载指示器避免界面卡顿:
      swift复制
      func fetchUserList(completion: @escaping (Result<[User], Error>) -> Void) {  
          activityIndicator.startAnimating() // 显示加载动画  
          URLSession.shared.dataTask(...) {  
              // ...解析逻辑  
              completion(.success(users))  
              // 或 completion(.failure(error))  
              DispatchQueue.main.async {  
                  activityIndicator.stopAnimating()  
              }  
          }  
      }  

关键技巧总结

  1. ??函数命名规范??

    • Swift使用驼峰式(如fetchUserList
    • Objective-C强调可读性(如downloadDataWithCompletionHandler:
  2. ??跨语言调用??

    • 在Swift中调用Objective-C方法需导入桥接头文件
    • Objective-C调用Swift方法时添加@objc标记:
      swift复制
      @objc func calculatePrice() -> Double { ... }  
  3. ??调试技巧??

    • 使用??Xcode断点调试??观察函数调用堆栈
    • 在控制台输入po [self methodSignatureForSelector:@selector(目标方法)]验证Objective-C方法是否存在

通过这三个真实场景的拆解,开发者可快速掌握iOS函数调用的核心逻辑,从事件响应到数据传递均能游刃有余。建议在Xcode中创建测试项目,逐行实践文中代码示例以加深理解。

搜索