代码之家  ›  专栏  ›  技术社区  ›  dicle

从nsobject类创建数组

  •  0
  • dicle  · 技术社区  · 6 年前

    我有一个包含3个属性的nsobject类调用详细信息。

     @interface Details : NSObject
    
    @property (nonatomic, nonnull, strong) UIImage *image; 
    @property (nonatomic, assign) NSInteger number; 
    @property (nonatomic, nonnull, strong) NSString *details;
    
    - (NSDictionary *_Nonnull)getMappedDictionary; @end
    

    这个班的动力是

    @interface Details()
    @property (nonatomic, nonnull) NSString *imageFormat;
    @property (nonatomic, nonnull) NSData *imageData;
    @end
    
    @implementation Details
    
    - (instancetype)init {
        if (self = [super init]) {
            _imageFormat = @"jpg";
        }
        return self;
    }
    
    - (NSData *)imageData {
        if (!_imageData) {
            _imageData = UIImageJPEGRepresentation(self.image, 1.0);
        }
        return _imageData;
    }
    
    - (NSInteger)number {
        return _number;
    }
    
    - (NSString *)details {
        return _details;
    }
    
    - (NSString *)getImageBase64 {
        NSString *base64String = @"";
        base64String = [self.imageData base64EncodedStringWithOptions:kNilOptions];
        return base64String;
    }
    
    static id ObjectOrNull(id object) {
        return object ?: [NSNull null];
    }
    
    - (NSDictionary *)getMappedDictionary {
        return @{ImageKey : ObjectOrNull([self getImageBase64]), NumberKey : @(_number), DetailKey : _details};
    }
    

    在另一个类调用请求类中,我想创建一个数组来保存details类的属性(image、number、details)

    - (NSMutableSet<Details *> *)details {
        if (!_details) {
            _details = [NSMutableSet new];
        }
        return _dDetails;
    }
    
    - (NSArray *)getMappedActionDetails {
        NSMutableArray *details = [NSMutableArray new];
        for (Details *detail in self.details) {
            [details addObject:[detail getMappedDictionary]];
        }
        return details;
    }
    

    但是我不能将这个类的属性作为数组…我错过了什么?任何帮助都是完美的!谢谢

    2 回复  |  直到 6 年前
        1
  •  1
  •   Sim.Li    6 年前
     -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]'
    

    意思是你用零创建一个字典。 对象[0]表示第一个对象为零。 所以我想当你用这个来编字典的时候。

    - (NSDictionary *)getMappedDictionary {
         return @{ImageKey : ObjectOrNull([self getImageBase64]), NumberKey : @(_number), DetailKey : _details};
    }
    

    ObjectOrNull([self getImageBase64]) 回零。

        2
  •  0
  •   Matic Oblak    6 年前

    从评论来看,问题实际上是试图在字典中插入nil对象:

    '***-[\u nsplaceholderdictionary initwithobjects:forkeys:count:]: 试图从对象[0]插入nil对象

    提供的代码将指向 getMappedActionDetails 最有可能插入 nil 对象。假设 ObjectOrNull 我敢打赌在你的一个模特身上 _details 财产是 . 也许解决办法是:

    - (NSDictionary *)getMappedDictionary {
        return @{ImageKey : ObjectOrNull([self getImageBase64]), NumberKey : @(_number), DetailKey : ObjectOrNull(_details)};
    }
    

    我也建议使用 exception breakpoints 以获得坠机的确切位置。