Objective-C使用块枚举的细节

对元素类型的要求

在 Objective-C 中,NSArray 只能存储对象类型,而不能直接存储基本类型(例如 int)。但是,可以将基本类型封装在 NSNumber 等对象中,然后将这些对象存储在 NSArray 中。这样,enumerateObjectsUsingBlock: 方法中的 obj 仍然是指向这些对象的指针。

objc 复制代码
NSArray *array = @[@1, @2, @3];
[array enumerateObjectsUsingBlock:^(NSNumber *obj, NSUInteger idx, BOOL *stop) {
    int value = [obj intValue];
    NSLog(@"Object: %@, Int Value: %d, Address: %p", obj, value, obj);
}];

obj 是一个指针变量,局部变量

obj 和 array 中对应位置的元素指向相同的内存地址,但它们不是同一个指针变量,而是两个指向同一对象的不同变量。

在 -enumerateObjectsUsingBlock: 方法中,块枚举会遍历数组,并将每个元素的指针赋值给 obj。因此,obj 是一个局部变量,在每次迭代时指向数组中当前遍历的元素。尽管它们指向同一对象,但 obj 是块中的局部变量,而数组中的元素是数组中的存储单元。

objc 复制代码
NSArray *array = @[@"one", @"two", @"three"];
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSLog(@"Object: %@, obj Address: %p, obj Pointer Address: %p, array[idx] Address: %p, array[idx] pointer Address: %p", obj, obj, &obj, array[idx], &array[idx]);
}];

循环引用问题

在 Objective-C 中使用 enumerateObjectsUsingBlock 时,同样需要注意循环引用问题。enumerateObjectsUsingBlock 会将块传递给枚举方法,如果块捕获了对自身或外部对象的强引用,这可能导致循环引用,尤其是当这个对象也强引用调用该块的对象时。

示例说明

假设有一个类 MyClass,其实例方法使用 enumerateObjectsUsingBlock

objc 复制代码
@interface MyClass : NSObject
@property (nonatomic, strong) NSArray *array;
@end

@implementation MyClass

- (void)enumerateArray {
    [self.array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        // 这里使用了 self
        NSLog(@"%@", self);
    }];
}

@end

在上述代码中,块捕获了 self 的强引用。如果 self 对象持有 array,这就形成了一个循环引用,导致 self 无法被释放。

解决方案

使用弱引用来打破循环引用,可以使用 __weak__block 关键字:

objc 复制代码
@implementation MyClass

- (void)enumerateArray {
    __weak typeof(self) weakSelf = self;
    [self.array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        // 这里使用了弱引用的 self
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (strongSelf) {
            NSLog(@"%@", strongSelf);
        }
    }];
}

@end

在这个修改后的代码中,使用 __weakself 的弱引用传递到块内,然后在块内将其转换为强引用以确保在使用过程中对象的生命周期被正确管理。

相关推荐
ajassi200010 小时前
开源 Objective-C IOS 应用开发(十四)传感器--陀螺仪和gps
ios·开源·objective-c
二流小码农12 小时前
鸿蒙开发:支持自定义组件的跑马灯
android·ios·harmonyos
2501_9151063213 小时前
iOS 抓包全流程指南,HTTPS 抓包、TCP 数据流分析与多工具协同的方法论
android·tcp/ip·ios·小程序·https·uni-app·iphone
3***49961 天前
Swift Experience
开发语言·ios·swift
疯笔码良1 天前
【IOS开发】Objective-C 与 Swift 的对比
ios
阿斌_bingyu7091 天前
uniapp实现android/IOS消息推送
android·ios·uni-app
QuantumLeap丶1 天前
《Flutter全栈开发实战指南:从零到高级》- 15 -本地数据存储
flutter·ios·dart
非专业程序员1 天前
精读GitHub - swift-markdown-ui
ios·swiftui·swift
法的空间1 天前
让 Flutter 资源管理更智能
android·flutter·ios
2501_915918412 天前
移动端 HTTPS 抓包实战,多工具组合分析与高效排查指南
数据库·网络协议·ios·小程序·https·uni-app·iphone