【问题标题】:How to remove nil object from NSMutableArray?如何从 NSMutableArray 中删除 nil 对象?
【发布时间】:2017-05-30 12:59:36
【问题描述】:

我的NSMutableArray 包含以下数据

<DoctorInfo: 0x15de99e0> (entity: DoctorInfo; id: 0x15defbe0 <x-coredata://39D9B/DoctorInfo/p8> ; data: {
    doctorName = nil;
    emailAdd = nil;
    hospitalName = nil;
    mobileNumber = nil;
    phoneNumber = nil;
}),
<DoctorInfo: 0x15de9b00> (entity: DoctorInfo; id: 0x15da5dc0 <x-coredata://39D9BED3/DoctorInfo/p10> ; data: {
    doctorName = nil;
    emailAdd = nil;
    hospitalName = nil;
    mobileNumber = nil;
    phoneNumber = nil;
})
)

如何使用nil 删除这些对象?我通过将NSMutableArray 更改为NSArray 尝试了以下代码,然后对其进行过滤,但它仍然无法正常工作:

 NSString *predString = [NSString stringWithFormat:@"(doctorName BEGINSWITH[cd] '%@')", nil];

    NSPredicate *pred = [NSPredicate predicateWithFormat:predString];

     self.filteredDocInfoArray = [self.unfilteredDocInfoArray filteredArrayUsingPredicate:pred];

【问题讨论】:

  • NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(DoctorInfo * evaluateObject, NSDictionary *bindings) { if (evaluatedObject.doctorName == nil) { return YES; } 返回否; }];

标签: ios objective-c


【解决方案1】:

您在这样的谓词字符串中测试 nil:

NSPredicate *pred = [NSPredicate predicateWithFormat: @"doctorName = nil"];

有关示例,请参阅the documentation

【讨论】:

    【解决方案2】:

    您不能将 nil 对象添加到数组。在您的情况下,您正在添加一个具有一些 nil 属性的对象!

    你可以试试这个:

    [yourArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    
        DoctorInfo *customObj = obj;
        if (customObj.doctorName) {
            //add obj to temp array
        }
    }];
    

    现在你可以用 tempArr 替换 yourArr

    如果你想使用NSPredicate,请参考this.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多