S. Birklin
S. Birklin

Reputation: 1375

Converting Array of Objects into Object of arrays

I have a class with some arrays of different types and let's say they're all filled with the same amount.

public class CoreLocationMap {

var type: [String] = []
var location: [Int] = []
var groupName: [NSString] = []
var x: [Float] = []

init() {}

}

I want something like a JSON Object:

var jsonObject = ({type = myString; location = 123; groupName = anotherString; x = 0.123}, {type = myString; location = 123; groupName = anotherString; x = 0.123}, ...)

It's not necessarily to have a jsonObject, but i want to capsule my variables in logical groups, so

type
location
groupName
x

should make a struct/object/whateever^^. If I use later for example a certain location i want to reference to the other variables in this group. I'm also pleased about other solutions. If you need more details please tell me.

Thanks!

Upvotes: 2

Views: 1299

Answers (3)

sehaswaran
sehaswaran

Reputation: 151

This library does the same thing for you JSONModel https://github.com/icanzilb/JSONModel

This library has the following method

    NSArray* jsonObjects = [YourModelClass arrayOfDictionariesFromModels: modelObjects];

this method returns the Array of Dictionaries from Array of Objects.

Now , you can use

NSJSONSerialization

Upvotes: 0

user1548843
user1548843

Reputation: 670

you can create model calss lets say locationModel like

  calss locationModel{
     var type:String
     var location : Int
     var groupName : String
     var x: Float

  // you can create Init method to init() model properties 
  // you can create custom method to fill values of model calss

  /* you create custom method that accept array as argument create 
    this class (locationModel) type of object in function load data
    from array to modelobject add modelobject in array and return
    this array.*/
 }

now you can create this model class object where you want to use and fill them with model class methods.

like if you want to use this in CoreLocationMap create location model and init it in your class and fill value.

and add this model objects in newly created array if you want array of object. hope this help you.

Upvotes: 2

giorashc
giorashc

Reputation: 13713

as you suggested you can use a struct to encapsulate your data:

struct LocationData {
   var type: String
   var location: Int
   var groupName: String
   var x: Float
}

and declare an array in your class :

var locationsData = Array<LocationData>()

add a function for adding elements :

func addLocationData(type: String, location: Int, groupName: String, x:Float) {
   // Add additional safety/limitation checks
   locationsData.append(LocationData(type: type, location: location, groupName: groupName, x: x) // structs have an implicit init method
}

Upvotes: 2

Related Questions