NSArray of NSDictionary - Returning NSDictionary when having only one dictionary in array, not Array of one object

时间:2015-05-12 23:37:14

标签: ios objective-c arrays dictionary

I am relatively new to Objective C. I have a NSArray containing NSDictionary objects. I am calling web service to fetch data. I have a PickerView and this is its DataSource (I have numberOfRows implemented):

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    // Configure the cell...
    cell.backgroundColor = UIColor.clearColor()

    return cell
}

This is my 'proba' with 3 NSDictionaries in Array:

enter image description here

This is my 'proba' with only 1 NSDictionary in Array

enter image description here

Problem is that I need to have 1 NSDictionoray object in Array when my service returns 1 Dictionary. How to fix this? Thanks

EDIT: My array from service, this is my selector

- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
 {
     NSString *proba = self.viewModel.searchResult.someArray[row];
     return nil;
}

'self.Result' is observed with RACObserver so I can use it my ViewModel.

This is result.Retailers with 3 dictionaries:

enter image description here

And this with 1 dictionary:

enter image description here

So yeah, when only oneObject, it returns only Dictionary

1 个答案:

答案 0 :(得分:2)

你的问题不明确,但是我猜你有一个web服务,如果有多个结果会返回一个数组,但只有结果本身,如果只有一个,你想要的是一个数组后一种情况就是一个结果。

您可以使用isKindOfClass:检查您的网络服务返回的值类,从而解决此问题。概括地说,这可能是:

id myWebServiceResult = ...;

if (![myWebServiceResult isKindOfClass:[NSArray class]]) // note the ! - not
{
   // the result is not an array, make it an array of one item
   myWebServiceResult = @[ myWebServiceResult ];
}

HTH