Rust Cocoa环境下如何遍历ICCameraDevice返回的NSArray对象
错误原因
你通过ICCameraDevice.mediaFiles()拿到的cam_media_files本质是*mut Object类型的裸指针,指向Objective-C的NSArray实例。Rust的for循环要求被遍历的对象实现IntoIterator trait,裸指针本身没有实现该trait,所以直接遍历会触发编译错误。你之前尝试调用的array、arrayWithObject都是用来创建新NSArray实例的方法,不能用来遍历已有的数组。
解决方案
方法1:按索引直接遍历(最简单)
直接通过NSArray提供的objectAtIndex方法按索引读取元素即可:
use cocoa::foundation::NSArray; use cocoa::foundation::NSUInteger; // 先获取数组总长度 let count: NSUInteger = unsafe { NSArray::count(cam_media_files) }; // 遍历索引逐个读取元素 for idx in 0..count { let media_file = unsafe { NSArray::objectAtIndex(cam_media_files, idx) }; println!(" 🤩📷 media_file: {:?}", media_file); }
方法2:封装迭代器(更符合Rust使用习惯)
如果你需要多次遍历NSArray,可以封装一个自定义迭代器避免重复写索引逻辑:
use cocoa::foundation::{NSArray, NSUInteger, Object}; struct NSArrayIter { array: *mut Object, current: NSUInteger, count: NSUInteger, } impl Iterator for NSArrayIter { type Item = *mut Object; fn next(&mut self) -> Option<Self::Item> { if self.current >= self.count { return None; } let item = unsafe { NSArray::objectAtIndex(self.array, self.current) }; self.current += 1; Some(item) } } // 使用迭代器遍历 let iter = NSArrayIter { array: cam_media_files, current: 0, count: unsafe { NSArray::count(cam_media_files) }, }; for media_file in iter { println!(" 🤩📷 media_file: {:?}", media_file); }
注意事项
- 所有调用
NSArraytrait方法的代码都需要包裹在unsafe块中,Objective-C runtime调用没有编译期安全保证,你需要自行确保cam_media_files是有效的NSArray指针,且遍历过程中数组不会被释放、元素不会被移除。 - 拿到
media_file指针后,如果需要使用它的具体属性和方法,可以转成对应的Objective-C对象类型指针操作。
内容的提问来源于stack exchange,提问作者Mikeumus
相关产品推荐
相关产品推荐

