Storing user input from text field into an NSArray - objective-c

I am trying to store user input text (in this case a book title) into an array so that I can output it in a table view in another xib.
I'm getting stuck trying to store the "bookTitle.text" info into my "userinfoArray". I know it probably has a simple solution and I know how to do it in C++ but not in Objective-C. Any tips, links etc. would be great.

NSMutableArray *userinfoArray = [[NSMutableArray alloc]init];
NSString *tempString = [[NSString alloc]initWithString:[bookTitle text]];
[userinfoArray addObject:tempString];
you can then access it later with:
[userinfoArray objectAtIndex:0];
NSMutableArray is very flexible. with addObject:object you can add as many things as you want, remove them with removeObjectAtIndex:index.
more here: NSMutableArray Class Reference
alternatively if you know what size your array will have you can use a normal NSArray: NSArray Class Reference which will work similar
sebastian

Try
userinfoArray = [NSArray arrayWithObject:[bookTitle text]];
Or if you want to create a longer array with more objetcs then
userinfoArray = [NSArray arrayWithObjects:[bookTitle text], secondObject, thirdObject, nil];
If you want to add or remove objects later then you may want to use NSMutableArray instead.
If this does not answer your question, then please try to be a bit more specific about your problem.

Related

How to fill NSArray in compile time?

In Objective-C, how to do something like is
int array[] = {1, 2, 3, 4};
in pure C?
I need to fill NSArray with NSStrings with the smallest overhead (code and/or runtime) as possible.
It's not possible to create an array like you're doing at compile time. That's because it's not a "compile time constant." Instead, you can do something like:
static NSArray *tArray = nil;
-(void)viewDidLoad {
[super viewDidLoad];
tArray = [NSArray arrayWithObjects:#"A", #"B", #"C", nil];
}
If it's truly important that you have this precompiled, then I guess you could create a test project, create the array (or whatever object) you need, fill it, then serialize it using NSKeyedArchiver (which will save it to a file), and then include that file in your app. You will then need to use NSKeyedUnarchiver to unarchive the object for use. I'm not sure what the performance difference is between these two approaches. One advantage to this method is that you don't have a big block of code if you need to initialize an array that includes a lot of objects.
use this
NSArray *array = [NSArray arrayWithObjects:str1,str2, nil];
As far as i understand you need a one-dimentional array
You can use class methods of NSArray.. For instance
NSString *yourString;
NSArray *yourArray = [[NSArray alloc] initWithObjects:yourString, nil];
If you need more, please give some more detail about your issue
Simple as that: NSArray<NSString*> *stringsArray = #[#"Str1", #"Str2", #"Str3", ...]; Modern ObjectiveC allows generics and literal arrays.
If you want shorter code, then NSArray *stringsArray = #[#"Str1", #"Str2", #"Str3", ...];, as the generics are optional and help only when accessing the array elements, thus you can later in the code cast back to the templatized array.

Objective-C: Parse string to object

I have a simple object. It has several NSString properties (propertyA, propertyB, propertyC).
I have a string (read from a csv file) in the following form:
this is value A, this is value B, this is value C
another row A, another row B
Notice that the second row is missing the last property.
I want to parse the string into my object. Currently I'm grabbing a line from the csv file and then doing this:
MyObject *something = [[MyObject alloc] init];
NSArray *split = [line componentsSeparatedByString:#","];
if (something.count > 0)
something.propertyA = [split objectAtIndex:0];
if (something.count > 1)
something.propertyB = [split objectAtIndex:1];
if (something.count > 2)
something.propertyC = [split objectAtIndex:2];
This works well, but feels really horrible and hacky!
Has anyone got any suggestions for how I can improve the code?
Take a look at this tread about parsing CSV Where can I find a CSV to NSArray parser for Objective-C?
Dave DeLong wrote a CSV-parser library, you can find it here: https://github.com/davedelong/CHCSVParser
Hope this helps :)
Here's a CSV parsing extension to NSString that I used in the past to handle CSV data.
http://www.macresearch.org/cocoa-scientists-part-xxvi-parsing-csv-data
If basically adds a -(NSArray *)csvRows method to NSString that returns a NSArray with each row on your data and a NSArray inside each row to handle the columns.
It's the simplest and cleanest way I found so far to deal with the ocasional CSV data that comes up.
Your approach actually seems pretty sound, given the input format of the file, and assuming that no individual items actually contain a comma within themselves. As others have mentioned, CSV and/or custom flat files require custom solutions to get what you want from them.
If the approach above gets you the data you want, then I say use it. If it doesn't though, perhaps you can share the actual problem you're experiencing (ie, what data are you getting out, and what were you expecting?)
Consider using an array of keys that correspond to MyObject property names. For example:
NSString *propertyNames[] = { #"property1", #"property2", #"property3" };
NSArray *values = [line componentsSeparatedByString:#","];
NSArray *keys = [NSArray arrayWithObjects:propertyNames count:[values count]];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:values forKeys:keys];
MyObject obj = [[MyObject alloc] init];
[obj setValuesForKeysWithDictionary:dict];
You could then consider adding an initWithDictionary: method to MyObject that calls setValuesForKeysWithDictionary. That would help streamline things a little further, allowing you to write the last two lines above as a single line:
MyObject obj = [[MyObject alloc] initWithDictionary:dict];

Objective-C identifier from NSString

I want to pass an NSString to a method and have that particular NSString name a new NSSMutableArray. Confusing? Programmatically looks like this:
+ (void)newMutableArrayWithName:(NSString*)theArrayName
{
NSLog(#"Creating an array that is named: %#",theArrayName);
NSMutableArray* theArrayName = [[NSMutableArray alloc] init];
}
Unfortunately, "theArrayName" is not affiliated with the argument passed to the method. Is there any way this is achievable?
The name of a variable is used by the compiler, and is set at compile-time, not at run time.
If you need to be able to associate a label with an array, I suggest that you use an NSDictionary to do something like this
NSString *theArrayName = #"My Cool Array";
NSMutableArray *theArray = [NSMutableArray array];
NSDictionary *theDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
theArray, theArrayName, nil];
You could have multiple "named" arrays in the dictionary, if you wanted, and could access them by the names that you gave them
[theDictionary objectForKey:#"My Cool Array"];
Look into key-value coding for setting the values of existing properties by the property's name, but it appears it can't create a new property. For that, you should just use a dictionary.

ViewTableUI cell loading problem

Helo! How can i convert a NSMutableArray object to a NSString ? i try to do something like
cell.textLabel.text = [cars objectAtIndex:indexPath.row];
But it doesn't work, my app crashes. If i do something like
cell.textLabel.text =#"yes";
The app loads very nicely(but instead of the elements from the "cars" NSMutableArray i have a view table filled with "yes") . Any idea what the problem is ?
Is the NSMutableArray alloc'd and init'd properly? If you don't call cars = [[NSMutableArray alloc] init] before you use it, the array will not respond to adding objects to it. Make sure that's not the case. Also make sure that the elements in the cars array are NSStrings.
Make sure your cards contains enough cars, if the indexPath.row is large than the cards's count-1, it will crash.

objective-c how to create an enumeration array with its string values as keys?

i have an enumeration say gender, now i want to associate it to string values to use in the view inside a picker view. It's cocoa-touch framework and objective-c as language.
So i don't know of a way to set the data source of the picker view as the enumeration, as could have been done in other frameworks. So i've been told i have to make array of enum values. and then i tried to add thos into an NSMutableDictionary with their respective string values.
So i ended up with
NSArray* genderKeys = [NSArray arrayWithObjects:#"Male",#"Female",nil] ;
NSArray* genderValues = [NSArray arrayWithObjects:[NSNumber numberWithInt:male],[NSNumber numberWithInt:female],nil];
for(int i =0;i<[genderKeys count];i++)
[_genderDictionary setValue:[genderValues objectAtIndex:i] forKey:[genderKeys objectAtIndex:i]];
and it's not working saying it's not a valid key, and i've read the key-coding article and i know now what's key and whats keypath, but still how can i solve that. It's ruining my life, Please help.
Sorry guys, i was using NSDictionary for _genderDictionary.But i had in my mind that it was nsmutable. Thank you all.
Be careful using UI text as keys into your database. What amount when you need to localise your application to french, chinese, arabic etc?
That works for me. Running this (your code, with the first line added so it would compile) seems to work fine.
NSMutableDictionary *_genderDictionary = [NSMutableDictionary dictionary];
NSArray* genderKeys = [NSArray arrayWithObjects:#"Male",#"Female",nil] ;
NSArray* genderValues = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],[NSNumber numberWithInt:2],nil];
for(int i =0;i<[genderKeys count];i++)
[_genderDictionary setValue:[genderValues objectAtIndex:i] forKey:[genderKeys objectAtIndex:i]];
NSLog()-ing _genderDictionary outputs this
{
Female = 2;
Male = 1;
}
edit: re-reading your question, makes me think what you are looking for is the delegate methods of UIPickerView... implementing –pickerView:titleForRow:forComponent: is where you set the text that appears in the picker. If you have an NSArray of genders, you would do something like return [_genderArray objectAtIndex:row]; That way you don't need to fuss around with a dictionary and keys.
edit 2: a picker's datasource can't be an NSArray or NSDictionary directly. It has to be an object that implements UIPickerView's datasource/delegate protocol (which I suppose you could do with a subclass of NSArray, but that'd be cah-ray-zay!).
If I understand you correctly, you try to create a pre-populated dictionary.
You could use [NSDictionary dictionaryWithObjectsAndKeys:] for that.
[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithUnsignedInt:0], #"Male",
[NSNumberWithUnsignedInt:1], #"Female", nil]