You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Objective C无法给子VC属性赋值,求对应Swift代码的OC实现方案

Objective-C 给子视图控制器属性赋值的正确实现

你遇到的报错根本原因是代码中将实例化的控制器声明为通用UIViewController类型,编译器无法识别自定义类的特有属性,和Swift的实现逻辑一致,做类型校验+强转即可解决。


前置要求

首先在当前实现文件的头部导入两个自定义控制器的头文件:

#import "PremiumCustomNavigationController.h"
#import "PremiumFeedbackViewController.h"

完整实现代码

和你的Swift代码逻辑完全对应:

NSString *storyboardName = @"Premium";
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle:nil];

// 校验并强转自定义导航控制器,对应Swift的as? PremiumCustomNavigationController
id feedbackNavVc = [storyboard instantiateViewControllerWithIdentifier:@"PremiumFeedbackNavViewController"];
if ([feedbackNavVc isKindOfClass:[PremiumCustomNavigationController class]]) {
    PremiumCustomNavigationController *navVc = (PremiumCustomNavigationController *)feedbackNavVc;
    
    // 校验并强转子控制器为自定义反馈VC,对应Swift的as? PremiumFeedbackViewController
    id childVc = navVc.childViewControllers.firstObject;
    if ([childVc isKindOfClass:[PremiumFeedbackViewController class]]) {
        PremiumFeedbackViewController *feedbackVc = (PremiumFeedbackViewController *)childVc;
        // 赋值注意:OC中id是预留关键字,Swift的id属性暴露到OC需要手动指定别名,比如用@objc(fileId)修饰Swift属性
        feedbackVc.fileId = self.fileDetails.id;
        feedbackVc.pageNumber = self.currentPageNumber;
        feedbackVc.pageCount = self.totalPageCount;
        
        [self presentViewController:navVc animated:YES completion:nil];
    }
}

特别提醒:id是Objective-C的预留关键字,不能直接作为属性名使用。如果你的Swift代码中定义的属性名是id,需要在Swift属性前加上@objc(fileId)手动指定暴露到OC的别名,OC端使用fileId访问即可避免关键字冲突。

内容的提问来源于stack exchange,提问作者iOSDude

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 10:27:02