0

I am inserting an Array into my database as a String and after fetching it I want it to convert it again to Array. So that I can fetch my values again and I can do next operation.

Here below is my array inserting into database(TestQuestion) as a String:

 let testQuestionModel : TestQuestion = NSEntityDescription.insertNewObject(forEntityName: "TestQuestion", into: AppDelegate.getContext()) as! TestQuestion
testQuestionModel.optionsArray = "\(question["options"] as! NSArray)"

Example: String Array I am getting from Database

(\n \"Rahul Abhyankar\",\n \"Pinkesh Shah\",\n \"Ramanan Ganesan\",\n \"Dr. Marya Wani\",\n \"\",\n \"\"\n)".

Here is 4 options you can see this is my string after fetching from Database.

1) Rahul Abhyankar.

2) Pinkesh Shah.

3) Ramanan Ganesan.

4) Dr. Marya Wani.

Now how can I convert it into array?

I tried some methods.

let arr = NSArray(object: quetion.optionsArray!). 

But I am getting only one object. How can I get my array values same as previous from this string array?

8
  • 2
    I would have say: let array:[String] = theLongString.components(separatedBy: ",") But, there is extra "\n", and extra (), so I guess there is also an issue on SAVING them. Cleary testQuestionModel.optionsArray = "\(question["options"] as! NSArray)" isn't the good way. Commented Aug 4, 2017 at 11:48
  • Then How can I do Any suggestion Please? Commented Aug 4, 2017 at 11:58
  • See the update on below answer Commented Aug 10, 2017 at 14:16
  • (\n \"Rahul Abhyankar\",\n \"Pinkesh Shah\",\n \"Ramanan Ganesan\",\n \"Dr. Marya Wani\",\n \"\",\n \"\"\n)". Doesn't look like a valid string. Commented Aug 10, 2017 at 14:19
  • @RAJAMOHAN-S It has to reflect na ? Commented Aug 10, 2017 at 14:28

3 Answers 3

1

I don't know about the actual type of the "option" in your code, so I set up a fake Elem struct to represent it. The remaining logic is independent of the type as long as you provide a conversion logic to and from String.

struct Elem {
    // let's say this is your element type in your array
    let foo: Int;
}

extension Elem: CustomStringConvertible {
    var description: String {
        // provide a logic to convert your element to string
        return "\(foo)";
    }
}

let arrayToSave = [
    Elem(foo: 1),
    Elem(foo: 2),
    Elem(foo: 3)
]

extension Elem {
    init(string: String) {
        // provide a function to construct your element type from a string
        self.init(foo: Int(string)!)
    }
}

let stringToSave = arrayToSave.map { $0.description }.joined(separator: "|")

// save this string

// at some point retrieve it from database, which hopefully same as the saved one

let retrivedString = stringToSave;

let retrivedArray = retrivedString.split(separator: "|").map { Elem(string: String($0)) }

print(retrivedArray) // [1, 2, 3]
Sign up to request clarification or add additional context in comments.

2 Comments

[\n\"RohanKrishna\",\n\"MadhurimaShah\",\nBhagya,\n\"PawanSharma\",\n\"\",\n\"\"\n]" How can I get this String to in Array?
why you're insisting on this kind of string construction? It'll easier to decode back to Array if you construct the string in a more structured way in the first place, like separating the elements by "|"
0

Here below is my array inserting into database (TestQuestion) as a String :

let testQuestionModel : TestQuestion = NSEntityDescription.insertNewObject(forEntityName: "TestQuestion", into: AppDelegate.getContext()) as! TestQuestion
testQuestionModel.optionsArray = "\(question["options"] as! NSArray)"

No, and No.
You are using -description method of an array to save it. Clearly no. What's wrong? Apple can't affirm that in next OS release, it won't add an extra character. In some more complex cases, it's added <NSArray <0x address> or stuff similar like that.

Suggestion 1:
Modify your entity to have an ARRAY (or usually a Set) of String. Learn about Core-Data relationship (but that's clearly a DataBase basic knownledge). A relationship one to many should be the thing to do.You could even keep in memory what were the choices, by adding for creating the entity Options, with a String property name (name of the option), another one boolean isChecked, etc.

Suggestion 2:
If you have a limited number of options (like says one to 5), add 5 options string to your entity, and iterate to set them

testQuestionModel.option1 = question["option"][0]
testQuestionModel.option2 = question["option"][1] (if it's of course not out of range for the array)
...

Suggestion 3: Not really recommended (in my opinion it's missing the whole advantage of the database, especially fetch and predicates, on previous sample you could fetched easily which options were checked), but if you still want to save them as a String, save them as JSON (ie. stringified). In pseudo code (I'm not sure about the exact syntax, there are no fail safe like try/catch, optional/wrapping):

let options = questions["options"] as [String]
let jsonData = JSONSerialization.data(withJSONObject: (question["options"], options:[])
let jsonString = String.init(data:jsonData encoding:.utf8)

To retrieve them:

let options = JSONSerialization.jsonObject(with data: myJSONString.data(encoding:.utf8), options:[]) as [String]

3 Comments

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write
So you chose the last solution which was, in my opinion the worst one? And did you remove before all the previous data inside your database which aren't correctly saved (which aren't JSON)?
Yes I removed previous data. and I have done some operations so what I am asking because of dependency. I choose last option.
0

done using Library SwiftyJSON.

 if let dataFromString = yourString?.data(using: String.Encoding.utf8, allowLossyConversion: false) {
        do{
            let json = try JSON(data: dataFromString)
            print(json)
            let arrayValue = json.rawValue as! NSArray

            print(arrayValue)
        } catch{
            print(error.localizedDescription)

        }
    }

Source: https://github.com/SwiftyJSON/SwiftyJSON

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.